Reputation: 1197
I apologize if this has been asked already.
I am just learning about SymPy and I'm wondering why it won't spit out a correct answer for what seems to be a simple equation.
from sympy.solvers import solve
from sympy import Symbol, simplify
from sympy.abc import x, alpha, sigma
alpha = Symbol('alpha')
x = Symbol('x')
sigma = Symbol('sigma')
solve((alpha - 0.5*(sigma**2))*((alpha + 0.5*(sigma**2)))**(-1)+ (1/7),sigma**2, simplify = True)
It spits out [2.0* alpha], which I know is incorrect. In fact, the answer should be [2.6666*alpha] or something like that. I'm assuming that SymPy is for some reason converting the number 2.666 to an integer string.
How can I fix this problem? Also, is there any way I could get the fractional form of the solution?
Upvotes: 0
Views: 119
Reputation: 19145
You can also use help(solve)
to read the docstring of solve that tells how to use the rational
keyword:
>>> solve(x-.3)
[0.300000000000000]
>>> solve(x-.3, rational=True)
[3/10]
Upvotes: 0
Reputation: 353604
You're probably using Python 2.7, so 1/7
is giving you integer division:
>>> 1/7
0
>>> 1./7
0.14285714285714285
>>> solve((alpha - 0.5*(sigma**2))*((alpha + 0.5*(sigma**2)))**(-1)+ (1/7),sigma**2, simplify = True)
[2.0*alpha]
>>> solve((alpha - 0.5*(sigma**2))*((alpha + 0.5*(sigma**2)))**(-1)+ (1./7),sigma**2, simplify = True)
[2.66666666666667*alpha]
If you want the fractional answer, maybe something like
>>> from sympy import Rational
>>> solve((alpha - (sigma**2)/2)*((alpha + (sigma**2)/2))**(-1)+ Rational(1,7),sigma**2, simplify = True)
[8*alpha/3]
Upvotes: 3