简体   繁体   中英

Python automatically converts the numerator and denominator of some fractions into big numbers. Why?

Here is an example:

x = frac(1,3)
x
Out[138]: Fraction(1, 3)
y = frac(5/39)
y
Out[140]: Fraction(288692283805801, 2251799813685248)
print(x+y)
3117876665102651/6755399441055744
x+y
Out[142]: Fraction(3117876665102651, 6755399441055744)

Why is 5/39 automatically converted to 288692283805801/2251799813685248? Using Python 3.7.8

5/39 is a floating point number, that's not representable as 5/39 exactly. The fraction with large numerator and denominator is the rational that exactly represents the floating point number that approximates 5/39.

Try fractions.Fraction(5, 39) instead.

A similar example is given in the docs for the fractions module, with Fraction(1.1) not returning Fraction(11, 10) as one might naively expect. https://docs.python.org/3/library/fractions.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM