Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

python - Is there a way to have fractions with roots?

Is there a way to have fractions (in python) with roots? When I write Fraction(np.sqrt(2), 2), it gives me 1/2, because Fraction takes ints as arguments. I want to have square root of 2 divided by 2, and keep the 2 under the root as to not lose precision while calculating.

Edit: I am using the package "fraction". I couldn't find "fractions" anywhere when I searched for the package to install.

question from:https://stackoverflow.com/questions/65923059/is-there-a-way-to-have-fractions-with-roots

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not entirely certain if the following is what you want, but, here it goes:

from fractions import Fraction as F
import numpy as np

print(F(F(np.sqrt(2)), 2).limit_denominator(max_denominator=100000))

print(5741/8119)     # with max_denominator=10000
print(33461/47321)
print(np.sqrt(2)/2)

Will produce:

33461/47321
0.7071067865500678
0.7071067813444348
0.7071067811865476

Update

Irrational to rational conversion cannot possibly preserve precision. No rational fraction can ever be equal to the relevant irrational number. All we can do is get to the closest value!


As a further insight, an enhancement proposal for inclusion of irrational numbers in fractions was rejected.

EDIT

If all you want is to display it mathematically in unicode:

from pylatexenc.latex2text import LatexNodes2Text

# To convert some latex unicode input to actual latex output
in_expr_unicode = r"""$frac{sqrt{2}}{2}$"""

out_latex = LatexNodes2Text().latex_to_text(in_expr_unicode)

print('          The math formula: ', out_latex)

which will output:

          The math formula:  √(2)/2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...