首页 > 解决方案 > Python:sympy TypeError:无法将表达式转换为浮点数

问题描述

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

目前我可以让它与诸如

但是,它不会接受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 :)

标签: pythonpython-3.xtypeerrorsympytaylor-series

解决方案


你得到错误:

TypeError: can't convert expression to float

由于参数按原样传递exprmath.sqrt(x)并且sympy不期望那样。

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

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

这同样适用于第 16 行。


推荐阅读