英文:
How to convert decimal values to fractions in a list of expressions in Python?
问题
import sympy as sp
from fractions import Fraction
M = sp.symbols('M')
diffs = [None, 0, 5*M/2 - 3.5, 0.5 - 3*M/2, -M, M/2 - 1.5, 0, 1.5 - 3*M/2]
# Convert terms of expression to fractions and format as "numerator/denominator"
diffs = [f"{Fraction(val).numerator}/{Fraction(val).denominator}" if isinstance(val, sp.Mul) else val for val in diffs]
print(diffs)
Output:
[None, 0, 5*M/2 - 7/2, 1/2 - 3*M/2, -M, M/2 - 3/2, 0, 3/2 - 3*M/2]
This code will convert the terms of the expression to fractions and format them as "numerator/denominator" as requested.
英文:
import sympy as sp
from fractions import Fraction
M = sp.symbols('M')
diffs = [None, 0, 5*M/2 - 3.5, 0.5 - 3*M/2, -M, M/2 - 1.5, 0, 1.5 - 3*M/2]
#Convert terms of expression to fractions (none of these 2 lines of code work)
diffs = [Fraction(float(val)).limit_denominator() if isinstance(val, float) else val for val in diffs]
#diffs = [sp.Rational(val).limit_denominator() if isinstance(val, float) else val for val in diffs]
print(diffs)
This is the output that I am getting where the terms of the expressions are written as decimals..
[None, 0, 5*M/2 - 3.5, 0.5 - 3*M/2, -M, M/2 - 1.5, 0, 1.5 - 3*M/2]
And this is the correct output that should be shown, indicating the terms as fractions (as long as they can be converted)
[None, 0, 5*M/2 - 5/2, 1/2 - 3*M/2, -M, M/2 - 3/ 2, 0, 3/2 - 3*M/2]
The truth is that I don't want it to print the terms in the results as a function with 2 parameters, for example like this Fraction(2,3)
or Rational(2,3)
, I need for example an output like this 2/3
答案1
得分: 1
[None, 0, 5*M/2 - 7/2, 1/2 - 3*M/2, -M, M/2 - 3/2, 0, 3/2 - 3*M/2]
英文:
>>> [nsimplify(i, rational=True) if i else i for i in diffs]
[None, 0, 5*M/2 - 7/2, 1/2 - 3*M/2, -M, M/2 - 3/2, 0, 3/2 - 3*M/2]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论