【问题标题】:How could I get square root of a symbol in python?如何在 python 中获得符号的平方根?
【发布时间】:2014-09-13 02:43:35
【问题描述】:

我在 python 中使用 math.sqrt 来计算某物的平方根,但“某物”是一个符号而不是一个已知值。我将那个“东西”用作以后使用的中间变量。

import math
from math import sqrt
x = Symbol('x')
y = math.sqrt(x)
print(y)

我如何得到错误消息

File "/Library/Python/2.7/site-packages/sympy/core/expr.py", line 207, in __float__
    raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float

看起来除了“math.sqrt”之外没有其他软件包可以计算平方根,有人知道我该如何解决这个问题吗?

【问题讨论】:

  • 这不应该被关闭。用户正在使用一个名为 sympy 的库。我建议用户应该更新问题以明确 Symbol() 来自这个库;这将消除混乱。

标签: python math numpy scipy sympy


【解决方案1】:

使用sympy时,应使用sympy中对符号进行操作的函数,而不是math.*中对浮点数进行操作的函数,例如

from sympy import *
x = Symbol('x')
y = sqrt(x)
print(y)

在本例中,代码使用了sympysqrt() 函数。

【讨论】:

  • 在这种情况下,使用sympy.Symbolsympy.sqrt 可能会更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 2012-09-29
  • 1970-01-01
相关资源
最近更新 更多