Assigning float as a dictionary key changes its precision (Python)

2024/10/4 9:32:13

I have a list of floats (actually it's a pandas Series object, if it changes anything) which looks like this:

mySeries:...
22      16.0
23      14.0
24      12.0
25      10.0
26       3.1
...

(So elements of this Series are on the right, indices on the left.) Then I'm trying to assign the elements from this Series as keys in a dictionary, and indices as values, like this:

{ mySeries[i]: i for i in mySeries.index }

and I'm getting pretty much what I wanted, except that...

{ 6400.0: 0, 66.0: 13, 3.1000000000000001: 23, 133.0: 10, ... }

Why has 3.1 suddenly changed into 3.1000000000000001? I guess this has something to do with the way the floating point numbers are represented (?) but why does it happen now and how do I avoid/fix it?

EDIT: Please feel free to suggest a better title for this question if it's inaccurate.

EDIT2: Ok, so it seems that it's the exact same number, just printed differently. Still, if I assign mySeries[26] as a dictionary key and then I try to run:

myDict[mySeries[26]]

I get KeyError. What's the best way to avoid it?

Answer

The dictionary isn't changing the floating point representation of 3.1, but it is actually displaying the full precision. Your print of mySeries[26] is truncating the precision and showing an approximation.

You can prove this:

pd.set_option('precision', 20)

Then view mySeries.

0    16.00000000000000000000
1    14.00000000000000000000
2    12.00000000000000000000
3    10.00000000000000000000
4     3.10000000000000008882
dtype: float64

EDIT:

What every computer programmer should know about floating point arithmetic is always a good read.

EDIT:

Regarding the KeyError, I was not able to replicate the problem.

>> x = pd.Series([16,14,12,10,3.1])
>> a = {x[i]: i for i in x.index}
>> a[x[4]]
4
>> a.keys()
[16.0, 10.0, 3.1000000000000001, 12.0, 14.0]
>> hash(x[4])
2093862195
>> hash(a.keys()[2])
2093862195
https://en.xdnf.cn/q/70623.html

Related Q&A

Installing jpype in Mountain Lion

I am trying to install jpype in Mountain Lion. I followed all the steps suggested in this post: How to install JPype on OS X Lion to use with Neo4j?However, there is a glitch with Mountain Lion. I hav…

Most efficient way to index words in a document?

This came up in another question but I figured it is best to ask this as a separate question. Give a large list of sentences (order of 100 thousands):[ "This is sentence 1 as an example", &qu…

python libclang bindings on Windows fail to initialize a translation unit from sublime text

Short description: using libclang to autocomplete code does not work with python that comes bundled with Sublime Text 3.Details: A small verifiable example is in the repo on GithubIn essence, there is …

How to create a simple Gradient Descent algorithm

Im studying simple machine learning algorithms, beginning with a simple gradient descent, but Ive got some trouble trying to implement it in python. Here is the example Im trying to reproduce, Ive got …

login_required decorator on a class based view in django

I have a working class based view. But when adding @login_required I get the error:AttributeError: function object has no attribute as_viewSomething is happening to the ResultListView here:from django.…

Generic way to get primary key from declaratively defined instance in SQLAlchemy

Does SQLAlchemy offer a generic way to get the primary key from a declaratively defined instance, so that if:Base = declarative_base()class MyClass(Base):__tablename__ = mytablekey = Column(Integer, pr…

Add column after another column

How can I add a column after another column to a database using Alembic or SQLAlchemy? That would be equivalent to this SQL clause: ALTER TABLE foo CHANGE COLUMN bar bar COLUMN_DEFINITION_HERE AFTER …

Scrapy Images Downloading

My spider runs without displaying any errors but the images are not stored in the folder here are my scrapy files:Spider.py:import scrapy import re import os import urlparse from scrapy.spiders import …

A full and minimal example for a class (not method) with Python C Extension?

Everywhere, I can easily find an example about writing a method with Python C Extensions and use it in Python. Like this one: Python 3 extension example$ python3 >>> import hello >>> …

Python: Grouping into timeslots (minutes) for days of data

I have a list of events that occur at mS accurate intervals, that spans a few days. I want to cluster all the events that occur in a per-n-minutes slot (can be twenty events, can be no events). I have …