python - 如何在方程输出中保留分数

标签 python math sympy fractions integral

我一直在使用 Python 来计算数学方程式。例如:

from sympy import Symbol, Derivative, Integral
x = Symbol('x')
d = Symbol('d')
Integral(8*x**(6/5)-7*x**(3/2),x).doit()

输出结果:

3.63636363636364*x**2.2 - 2.8*x**2.5

有没有办法将此答案显示为分数而不是小数?我希望看到输出为:

(40/11)*x**(11/5)-(14/5)*x**(5/2)+C

最佳答案

SymPy 具有用于有理数的 Rational 类。

from sympy import *
# other stuff 
integrate(8*x**Rational(6, 5) - 7*x**Rational(3, 2),x)

不需要 Integral().doit() 除非你真的想打印出未评估的表格。

其他版本:

integrate(8*x**Rational('6/5') - 7*x**Rational('3/2'),x)

(可以从字符串中解析出有理数);

integrate(8*x**(S.One*6/5) - 7*x**(S.One*3/2),x)

(使用“1”的 SymPy 对象开始计算将其转换为 SymPy 对象操作,避免普通的 Python 除法,这会给出一个 float )

关于python - 如何在方程输出中保留分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45651029/

相关文章:

python - Pygame |属性错误: 'Background' object has no attribute 'image'

Sympy 积分的逐步求解

python - Paradoxon : silent crash on Python's ctypes. CDLL 在导入时出现,但在直接运行时却没有 - 这怎么可能?

python - unittest.TestCase 获取 `TypeError: Error when calling the metaclas bases __init__() takes exactly 2 arguments (4 given)`

math - 圣人数学 : how to check if two expressions are equivalent?

java - 各种形状的面积和周长计算

R - 多列 fiddle 图

sympy - SymPy 三角函数的周期性

python - 仅一个循环的排序和非排序排列