英文:
sympy.Rational vs fractions.Fraction Comparison
问题
有区别吗?如果有,是什么?有什么优缺点?如果在Python中有其他实现有理数的方式,可以在比较中包括那些。
英文:
Are there differences? if so, what are they? What are the advantages and disadvantages? If there are other implementations of rational numbers in python, feel free to include those in the comparison.
答案1
得分: 0
如果你只是在寻找一个用于普通数值计算的有理数实现,那么最好使用fractions.Fraction
,它专门用于这种情况。SymPy的Rational
类有一些不同,因为它是符号表达式框架的一部分,与简单数字的实现相比,它带有一些额外开销。与其他替代方案相比,只有在使用SymPy进行符号计算时才真正有意义使用SymPy的Rational
。
在内部,SymPy本身将使用其QQ
类型进行更高效的有理数数值计算。如果安装了gmpy2,则QQ
指的是gmpy2.mpq
,它比Rational
或Fraction
都更高效。如果没有安装gmpy2,则QQ
指的是SymPy的内部PythonMPQ
类型,它类似于Fraction
。
英文:
If you are just looking for an implementation of rational numbers for ordinary numeric calculations then it is better to use fractions.Fraction
which is intended purely for that case. SymPy's Rational
class is somewhat different because it is part of a framework of symbolic expressions and that carries some overhead compared to just an implementation of simple numbers. Compared to the alternatives it only really makes sense to use SymPy's Rational
as part of symbolic calculations with SymPy.
Internally SymPy itself will use its QQ
type for more efficient numeric calculations with rational numbers. If gmpy2 is installed then QQ
refers to gmpy2.mpq
which is much more efficient than either Rational or Fraction. If gmpy2 is not installed then QQ
refers to SymPy's internal PythonMPQ
type which is similar to Fraction
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论