Domanda

I'm new to Sympy, and have realized it is quite nice for calculating and simplifying algebraic expressions.

However, when when I write fractions of real numbers it returns zero (no problem with fractions of symbols like 'x'). What am I doing wrong?

from sympy import *

1./2
Out[2]: 0.5

1/2
Out[3]: 0
È stato utile?

Soluzione

it's because python (2.7) needs a float in denominator or numerator to return a float.

in python 3.x any division returns a float

You can also 'fix' in python 2.7 that by using :

from __future__ import division

In fact python follow the integer division rules and return an integer and not a float number

Altri suggerimenti

1/2 isn't using SymPy at all. This is just evaluated by Python. Take a read of http://docs.sympy.org/latest/tutorial/gotchas.html#two-final-notes-and (I actually recommend reading through the whole SymPy tutorial).

Basically, if you are using SymPy, you probably want a rational number, which you can get with Rational(1, 2). An easier way to type this is S(1)/2. The S function converts 1 into SymPy's Integer(1), which then becomes a Rational when divided by.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top