【发布时间】:2020-12-28 21:54:21
【问题描述】:
我制作了一个计算器,可以将任何给定函数近似为输入。他们后来我想让它计算一个积分,但是写完之后:
function = str(input("The function that must be expanded and integrated: "))
它不打印一个数字,而是一个值。这是我的代码:
from sympy.functions import sin,cos,tan
from sympy.abc import x
from sympy import *
from sympy import series
from math import *
function = str(input("The function that must be expanded and integrated: "))
x0 = int(input("Point of development: "))
n = int(input("Amount of expressions: "))
print(series(function, x, x0, n))
N = int(input("Amount of summs (Bigger number is more accurate but takes longer time): "))
a = int(input("Integrate from: "))
b = int(input("Integrate to: "))
# We will use the midpoint method to integrate the function
def integrate(N, a, b):
def f(x):
return series(function, x, x0, n)
value=0
value=2
for n in range(1, N+1):
value += f(a+((n-(1/2))*((b-a)/N)))
value2 = ((b-a)/N)*value
return value2
print("...................")
print("Here is your answer: ")
print(integrate(N, a, b))
我想,这是因为我的输入是一个字符串。但是我不能选择我的输入为整数,因为exp(-x**2) 不是整数。如果是这样,我怎样才能在我的计算器中输入任何函数并仍然得到一个值?
【问题讨论】:
-
你需要将字符串映射到一个函数来执行。如果您想输入
'exp(-x**2)'作为字符串,您还需要将其解析为要执行的内容 -
为什么要设置
value=0和下一行value=2?为什么N、a和b是integrate的参数,而不是function、x0和n。我更喜欢使用 all 作为参数,或者不使用它们。 -
为什么同时使用泰勒多项式逼近和中点逼近? 要么 直接对原始函数使用中点规则 或 精确/分析地积分泰勒多项式会更好吗?
标签: python integration taylor-series