I am using sympy and numpy to solve the following the problem:
Given a point (x0, y0) and a curve y=a*x**2+b*x+c, compute the minimal distances of (x0, y0) to (x,y).
from sympy.core.symbol import symbols
from sympy.solvers.solvers import solve
from sympy.utilities.lambdify import lambdify
x, y = symbols('x y')
a,b,c, x0, y0 = symbols('a b c x0 y0')
y = a*x**2 + b*x + c
dist2 = (x-x0)**2 + (y-y0)**2
sol = solve(dist2.diff(x), x)
dist2_diff_solve = lambdify( (x0,y0,a,b,c), solve(dist2.diff(x),x), modules='numpy')
Until now, every thing is fine. I can even get some results:
dist2_diff_solve(1, 1, 1, 1, 1)
[0.31718264650678707, (-0.9085913232533936-0.8665105933073626j),
(-0.9085913232533936+0.8665105933073626j)]
However, with another group of parameters, I have problems:
dist2_diff_solve(664515.9375, 3998106.0, 0.053674994761459802, -71340.561832823907, 23709057427.266102)
*** ValueError: negative number cannot be raised to a fractional power
I think this is a bug from lambdify, as I can do the following:
sol[0].evalf(subs={x0:664515.9375, y0:3998106.0, a:0.053674994761459802, b:-71340.561832823907, c:23709057427.266102})
664515.759983973 + .0e-19*I
I need lambdify because I need to compute a large number (~100K) of computation (vectorize) at one time. Can any one confirm this is a bug from lambdify? Any comments / suggestions are welcome.
Why Is the Runtimewarning: Invalid Value Encountered in double_scalars Error Happening? The runtimewarning: invalid value encountered in double_scalars error happens when web developers try to perform certain mathematical operations that include numbers at the opposite end of the spectrum.
The lambdify function translates SymPy expressions into Python functions. If an expression is to be evaluated over a large range of values, the evalf() function is not efficient. lambdify acts like a lambda function, except it converts the SymPy names to the names of the given numerical library, usually NumPy.
A double scalar is a value of type double . It is called scalar to differentiate it in numpy from double arrays.
I found one related question: negative pow in python
and solved this problem simply by adding +0j to a, that is:
dist2_diff_solve(664515.9375+0j, 3998106.0, 0.053674994761459802, -71340.561832823907, 23709057427.266102)
[(664515.7418921513+3.552713678800501e-15j), (664600.9266076663+5.329070518200751e-15j), (664564.8069210749-1.4210854715202004e-14j)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With