在一定范围内更改数学函数

时间:2016-12-19 09:02:26

标签: python if-statement range

我需要编写一个在特定x位置使用不同值的数学函数。 (它代表穿过不同媒介的光线)

我首先尝试制作一个非常简单的代码,看看它是否有用,不幸的是,由于我没有图表,我似乎无法正确输入它。

def function(x):
    if x < 10:
       a = 1
    if (10.0 <= x <= 20.0):
       a = 0.5
    if x > 20:
       a = -1
    return x*a

x = np.arange (0,30,90)
y = function(x)
plt.plot(x,y,'b')
plt.show()

由于

2 个答案:

答案 0 :(得分:0)

正如Bob__所写,你应该使用map函数。

import numpy as np

def function(x):
    if x < 10:
       a = 1
    if (10.0 <= x <= 20.0):
       a = 0.5
    if x > 20:
       a = -1
    return x*a

x = np.arange (0,30,1)
y = map(function,x)
print(*y)

运行此命令会输出以下值:

0 1 2 3 4 5 6 7 8 9 5.0 5.5 6.0 6.5 7.0 7.5 8.0 8.5 9.0 9.5 10.0 -21 -22 -23 -24 -25 -26 -27 -28 -29

我更改了arange函数中的值以覆盖映射函数中的每个条件。 map函数将它的第一个参数应用于它的第二个可迭代参数的每个元素。

答案 1 :(得分:0)

该行

x = np.arange (0,30,90)

肯定是错的。 OP是否正在尝试创建一个包含0到90之间的30个数字的列表,或者是从0到30的90个数字的列表,函数Fn::Sub intrinsic function按以下顺序要求其参数: start 间隔,结束的间隔和步骤(值之间的间距)。

然后,x被传递给function,它(根据它的编写方式)期望接收单个值作为参数,而不是列表。实际上,行if x < 10:会生成错误:

  

ValueError:具有多个元素的数组的真值是不明确的。

可以通过更改function或创建列表y的方式来解决此问题。

另一件我不清楚的事情(鉴于OP所面临的数学问题的解释)是function应该是非连续的(因为它是)或者是否是简化的结果实际的代码。我将在以下代码段中显示这两种情况:

import numpy as np
import matplotlib.pyplot as plt

# OP function... almost
def func_1(x):
    if x < 10:
       a = 1
    elif x <= 20.0:
       a = 0.5
    else:
       a = -1
    return a * x

# Continuous function based on OP function slopes
def func_2(x):
    if x < 10:
       return x
    elif x <= 20.0:
       return 5 + 0.5 * x
    else:
       return 35 - x

# The correct order of the parameters is start, stop, step
x = np.arange (0,30,0.1)

# lists of calculated values created by list comprehensions
y_1 = [func_1(i) for i in x]
y_2 = [func_2(i) for i in x]

plt.plot(x, y_1, 'r')
plt.plot(x, y_2, 'b')

plt.show()

产生这个结果:

numpy.arange()