I'm new to Sympy, and have realized it is quite nice for calculating and simplifying algebraic expressions.
我是Sympy的新手,并且已经意识到它非常适合计算和简化代数表达式。
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?
但是,当我写出实数的分数时,它返回零(像'x'这样的符号分数没有问题)。我究竟做错了什么?
from sympy import *
1./2
Out[2]: 0.5
1/2
Out[3]: 0
2 个解决方案
#1
7
it's because python (2.7) needs a float in denominator or numerator to return a float.
这是因为python(2.7)需要浮点分母或分子来返回浮点数。
in python 3.x any division returns a float
在python 3.x中,任何分区都返回一个浮点数
You can also 'fix' in python 2.7 that by using :
您还可以使用以下命令在python 2.7中“修复”:
from __future__ import division
In fact python follow the integer division rules and return an integer and not a float number
实际上python遵循整数除法规则并返回整数而不是浮点数
#2
0
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).
1/2根本没有使用SymPy。这只是由Python评估。阅读http://docs.sympy.org/latest/tutorial/gotchas.html#two-final-notes-and(我实际上建议阅读整个SymPy教程)。
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.
基本上,如果您使用SymPy,您可能需要一个有理数,您可以使用Rational(1,2)。输入它的更简单方法是S(1)/ 2。 S函数将1转换为SymPy的Integer(1),然后在除以时成为Rational。
#1
7
it's because python (2.7) needs a float in denominator or numerator to return a float.
这是因为python(2.7)需要浮点分母或分子来返回浮点数。
in python 3.x any division returns a float
在python 3.x中,任何分区都返回一个浮点数
You can also 'fix' in python 2.7 that by using :
您还可以使用以下命令在python 2.7中“修复”:
from __future__ import division
In fact python follow the integer division rules and return an integer and not a float number
实际上python遵循整数除法规则并返回整数而不是浮点数
#2
0
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).
1/2根本没有使用SymPy。这只是由Python评估。阅读http://docs.sympy.org/latest/tutorial/gotchas.html#two-final-notes-and(我实际上建议阅读整个SymPy教程)。
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.
基本上,如果您使用SymPy,您可能需要一个有理数,您可以使用Rational(1,2)。输入它的更简单方法是S(1)/ 2。 S函数将1转换为SymPy的Integer(1),然后在除以时成为Rational。