だから私はでintegral(function, n=1000, start=0, stop=100)
定義された関数を持っていますnums.py
:
def integral(function, n=1000, start=0, stop=100):
"""Returns integral of function from start to stop with 'n' rectangles"""
increment, num, x = float(stop - start) / n, 0, start
while x <= stop:
num += eval(function)
if x >= stop: break
x += increment
return increment * num
しかし、私の先生 (私のプログラミングのクラス) は、を使用して入力を取得しinput()
、それを返す別のプログラムを作成することを望んでいます。ので、私は持っています:
def main():
from nums import integral # imports the function that I made in my own 'nums' module
f, n, a, b = get_input()
result = integral(f, n, a, b)
msg = "\nIntegration of " + f + " is: " + str(result)
print(msg)
def get_input():
f = str(input("Function (in quotes, eg: 'x^2'; use 'x' as the variable): ")).replace('^', '**')
# The above makes it Python-evaluable and also gets the input in one line
n = int(input("Numbers of Rectangles (enter as an integer, eg: 1000): "))
a = int(input("Start-Point (enter as an integer, eg: 0): "))
b = int(input("End-Point (enter as an integer, eg: 100): "))
return f, n, a, b
main()
Python 2.7 で実行すると、正常に動作します。
>>>
Function (in quotes, eg: 'x^2'; use 'x' as the variable): 'x**2'
Numbers of Rectangles (enter as an integer, eg: 1000): 1000
Start-Point (enter as an integer, eg: 0): 0
End-Point (enter as an integer, eg: 100): 100
Integration of x**2 is: 333833.5
integral
ただし、Python 3.3 (私の先生はこれを使用することを主張しています) では、まったく同じ入力で、関数でエラーが発生します。
Traceback (most recent call last):
File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\integration.py", line 20, in <module>
main()
File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\integration.py", line 8, in main
result = integral(f, n, a, b)
File "D:\my_stuff\Google Drive\Modules\nums.py", line 142, in integral
num += eval(function)
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
さらに、integral
単独で (Python 3.3 で) 正常に動作します。
>>> from nums import integral
>>> integral('x**2')
333833.4999999991
そのため、私のクラスのプログラムに問題があると思います...どんな助けも大歓迎です。ありがとう :)