如何在Python中将列表中的十进制值转换为分数表达式?

huangapple go评论75阅读模式
英文:

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]

huangapple
  • 本文由 发表于 2023年6月29日 18:51:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580346.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定