stderr
stderr

Reputation: 1118

sympy lambdify RuntimeWarning: invalid value encountered in double_scalars

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.

Upvotes: 7

Views: 13119

Answers (1)

stderr
stderr

Reputation: 1118

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)]

Upvotes: 3

Related Questions