我有(由 SymPy 自动生成的)表达式,包括 sqrt 函数,在 sqrt 下有大数字,在它前面有小乘数。所以总体结果必须在浮点范围内,但 sqrt - 下的值不在。我使用 lambdify 命令将此表达式转换为 Python 函数。调用此函数得到异常:
from sympy import *
t = symbols("t")
k = 10
f = 2 * 10 ** (- k) * sqrt(10 ** (2 * k) * t ** 2 + 1)
print(f)
F = lambdify(t, f)
t0 = 10 ** 10
T = np.arange(t0, 2 * t0, t0 / 4)
print(T)
F(T)
输出:
2.0e-10*sqrt(100000000000000000000*t**2 + 1)
[1.00e+10 1.25e+10 1.50e+10 1.75e+10]
AttributeError: 'float' object has no attribute 'sqrt'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15740/1035914544.py in <module>
8 T = np.arange(t0, 2 * t0, t0 / 4)
9 print(T)
---> 10 F(T)
<lambdifygenerated-11> in _lambdifygenerated(t)
1 def _lambdifygenerated(t):
----> 2 return 2.0e-10*sqrt(100000000000000000000*t**2 + 1)
TypeError: loop of ufunc does not support argument 0 of type float which has no callable sqrt method
对于k = 2
代码正常工作:
0.02*sqrt(10000*t**2 + 1)
[1.00e+10 1.25e+10 1.50e+10 1.75e+10]
array([2.0e+10, 2.5e+10, 3.0e+10, 3.5e+10])
有没有办法在不手动重写表达式的情况下解决这个问题?
UPD:看起来这是 NumPy 的问题:
import numpy as np
k = 10
def F1(t):
return np.sqrt( (10 ** (- k)) ** 2 * 10 ** (2 * k) * t ** 2 + 1)
def F2(t):
return 10 ** (- k) * np.sqrt(10 ** (2 * k) * t ** 2 + 1)
print(F1(10 ** 5))
print(F2(10 ** 5))
第一次通话有效,第二次通话 - 不!