Float to Fraction conversion in Python

2024/10/14 17:21:14

While doing exercise on the topic of float type to Fraction type conversion in Python 3.52, I found the difference between the two different ways of conversion.

The first method is:

>>> from fractions import Fraction
>>> x = 1232.23
>>> f = Fraction(*x.as_integer_ratio())
>>> print(f)
2709702426188841/2199023255552      #Answer

The second method is:

>>> from fractions import Fraction
>>> x = 1232.23
>>> f = Fraction(str(x))
>>> print(f)
123223/100                          #Answer

I want to know the reason behind these two different answers? Sorry if this is a stupid question , I am new to programming and Python.

Edited: I found a way to convert inaccurate fraction obtained by first method to accurate by limit_denominator method:

>>> from fractions import Fraction
>>> x = 1232.23
>>> f = Fraction(*x.as_integer_ratio())
>>> f = f.limit_denominator(100)     
>>> print(f)
123223/100
Answer

Yet again it's because floating point numbers aren't stored in base-10 (decimal), but in base-2 (binary).

A number that is finite length in base-10 might be a repeating decimal in base-2. And because floats are a fixed size, that repeating decimal gets truncated, resulting in inaccuracies.

When you use as_integer_ratio for a number that's a repeating decimal in base-2, you will get you a somewhat silly fraction as a result of the slight inaccuracies in the base-10 to base-2 conversion. If you divide those two numbers, the value will be very close to to your original number.

For instance, while 1/10 = 0.1 in base-10 and is not a repeating decimal, it is in fact a repeating decimal in base-2. Just like 1/3 = 0.333... in base-10.

>>> (0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)

If Python's output was exact, you would see this even when you enter just 0.1 in the prompt, by getting something like 1.00000...01 as the output. But Python hides this inaccuracy from you in the general case, leading to confusion.

https://en.xdnf.cn/q/69388.html

Related Q&A

How to update an SVM model with new data

I have two data set with different size.1) Data set 1 is with high dimensions 4500 samples (sketches).2) Data set 2 is with low dimension 1000 samples (real data). I suppose that "both data set ha…

Expanding NumPy array over extra dimension

What is the easiest way to expand a given NumPy array over an extra dimension?For example, suppose I have>>> np.arange(4) array([0, 1, 2, 3]) >>> _.shape (4,) >>> expand(np.…

Django-Haystack giving attribute error?

I am trying to use Haystack and Whoosh with my Django app. I followed the steps on Haystack docs, but i am getting this error when i do a searchAttributeError at /search/ module object has no attribute…

python calendar with holidays [duplicate]

This question already has answers here:Closed 12 years ago.Possible Duplicate:Holiday Calendars, File Formats, et al. Hi, Is there a calendar library in Python with which I can check for holidays, com…

How to choose your conda environment in Jupyter Notebook

I installed Anaconda 5.3 with Python 3.7 (root environment). After that I created a new environment (py36) using Python 3.6I activated the new environment with activate py36 conda env list shows that t…

How do I stagger or offset x-axis labels in Matplotlib?

I was wondering if there is an easy way to offset x-axis labels in a way similar to the attached image.

graphviz segmentation fault

Im building a graph with many nodes, around 3000. I wrote a simple python program to do the trick with graphviz, but it gives me segmentation fault and I dont know why, if the graph is too big or if im…

how to pass char pointer as argument in ctypes python

Please help me in converting below line of c++ code into ctypes python:Ret = openFcn(&Handle, "C:\\Config.xml");below are the declarations of each:typedef uint16_t (* OpenDLLFcnP)(void **…

Restarting a Python Interpreter Quietly

I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What…

Unique lists from a list

Given a list I need to return a list of lists of unique items. Im looking to see if there is a more Pythonic way than what I came up with:def unique_lists(l):m = {}for x in l:m[x] = (m[x] if m.get(x) !…