如何在 sympy 表达式中用有理数替换浮点数? [英] How do I replace floats with rationals in a sympy expression?

查看:34
本文介绍了如何在 sympy 表达式中用有理数替换浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自 sympy 计算的表达式:

sqrt(pi)*(0.333333333333333*a + 0.333333333333333*b - 2.66666666666667*c**2)

其中 a,b,c 是符号,并希望对其进行解析,以便将浮点数替换为像 in 中的有理数

sqrt(pi)*(1/3*a + 1/3*b - 8/3*c**2)

我知道如何手工制作,

In[24] Rational(str(0.3333333333333333)).limit_denominator(1000)出[24]:1/3

但不太知道如何解析原子并仅选择浮点数,然后代回有理数近似值.

在表达式中进行这些替换的最聪明方法是什么?

解决方案

使用 nsimplify:

<预><代码>>>>打印(nsimplify(sqrt(pi)*(0.333333333333333*a + 0.333333333333333*b - 2.66666666666667*c**2)))sqrt(pi)*(a/3 + b/3 - 8*c**2/3)

I have an expression from a sympy calculation:

sqrt(pi)*(0.333333333333333*a + 0.333333333333333*b - 2.66666666666667*c**2)

where a,b,c are symbols, and would like to parse it so that the floats are replaced with rationals like in

sqrt(pi)*(1/3*a + 1/3*b - 8/3*c**2)

I know how to do one by hand,

In[24] Rational(str(0.333333333333333)).limit_denominator(1000)

Out[24]: 1/3

but do not quite know how to go about parsing the atoms and picking only the ones that are floats, and substituting back the rational number approximation.

What is the smartest way of doing these substitutions in the expression?

解决方案

Use nsimplify:

>>> print(nsimplify(sqrt(pi)*(0.333333333333333*a + 0.333333333333333*b - 2.66666666666667*c**2)))
sqrt(pi)*(a/3 + b/3 - 8*c**2/3)

这篇关于如何在 sympy 表达式中用有理数替换浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆