繁体   English   中英

Python:sympy TypeError:无法将表达式转换为浮点数

[英]Python : sympy TypeError: can't convert expression to float

目前,我正在研究一个计算器,在确定定积分时,它的工作原理类似于“真实”计算器。

目前我可以让它与功能一起工作,例如

  • sin(x)
  • cos(x)
  • e**x
  • n*x**x

但是,它不会在我的代码中接受math.sqrt(x)作为函数,它只是指出,

File "C:\Users\Nikolai Lund Kühne\.spyder-py3\integration.py", line 6, in <module>
  print(series(math.sqrt(x), x, x0=0, n=6))

File "C:\ProgramData\Anaconda3\lib\site-packages\sympy\core\expr.py", line 327, in __float__
  raise TypeError("can't convert expression to float")

TypeError: can't convert expression to float

我的代码是:

from sympy.functions import sin,cos
from sympy.abc import x
from sympy import series
from pprint import pprint
# Indsæt her funktionen f(x), variablen x, udviklingspunktet x0 og antal led n
print(series(math.sqrt(x), x, x0=0, n=6))

N = int(input("Antal summer(flere summer er mere præcist): "))
a = int(input("Integrer fra: "))
b = int(input("Integrer til: "))

# Vi anvender Midpoint metoden til integration og skriver funktionen ind, som skal integreres

def integrate(N, a, b):
    def f(x):
        return series(math.sqrt(x), x, x0=0, n=6)
    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("Her er dit svar: ")
print(integrate(N, a, b))

任何人都可以在这里帮助我,非常感谢。

免责声明:我对编程和 Python 很陌生,希望得到任何帮助。 抱歉奇怪的设置,我在写问题时习惯了 LaTeX 和 MathJax :)

你得到错误:

TypeError: can't convert expression to float

由于作为expr传递的参数是math.sqrt(x) ,而sympy并不期望这一点。

math.sqrt(x)更改为x**0.5

print(series(x**0.5, x, x0=0, n=6))

这同样适用于第 16 行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM