Is there a way to have fractions with roots?

Viewed 543

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.

2 Answers

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

As a comment suggested, I found sqrt in the sympy package. For example sympy.sqrt(8) produces 2*sqrt(2), so it doesn't just keep the number under the root as not to lose precision, it also lets me make operations with it and simplifies it.

Related