Python - Converting an array to a list causes values to change

2024/10/9 4:21:44
>>> import numpy as np
>>> a=np.arange(0,2,0.2)
>>> a
array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,  1.4,  1.6,  1.8])
>>> a=a.tolist()
>>> a
[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0, 1.2000000000000002, 1.4000000000000001, 1.6, 1.8]
>>> a.index(0.6)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: 0.6 is not in list

it appears that some values in the list have changed and I can't find them with index(). How can I fix that?

Answer

0.6 hasn't changed; it was never there:

>>> import numpy as np
>>> a = np.arange(0, 2, 0.2)
>>> a
array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,  1.4,  1.6,  1.8])
>>> 0.0 in a
True # yep!
>>> 0.6 in a
False # what? 
>>> 0.6000000000000001 in a
True # oh...

The numbers in the array are rounded for display purposes, but the array really contains the value you subsequently see in the list; 0.6000000000000001. 0.6 cannot be precisely represented as a float, therefore it is unwise to rely on floating-point numbers comparing precisely equal!

One way to find the index is to use a tolerance approach:

def float_index(seq, f):for i, x in enumerate(seq):if abs(x - f) < 0.0001:return i

which will work on the array too:

>>> float_index(a, 0.6)
3
https://en.xdnf.cn/q/118626.html

Related Q&A

Understand Python Function [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable…

how to download linkedin (save as pdf option) using python

Image what i want to download.Image is of LinkedIn profile page of my friend i want to click on that save-as-pdf option for many users.can that be downloaded using python code? for different users? o…

My tkinter entry box is printing .!entry instead of what is entered

from tkinter import * def _name_():businessname=entry_bnprint(businessname) edit_bar=Tk() name=Label(edit_bar,text="Name:").grid(row=0) entry_bn=Entry(edit_bar) entry_bn.grid(row=0,column=1) …

How to get an average from a row then make a list out of it [duplicate]

This question already has answers here:Reading a CSV file, calculating averages and printing said averages(2 answers)Closed 6 years ago.If I have a csv data that gives two row values of:years grades 20…

Beautiful soup: Extract everything between two tags when these tags have different ids

Beautiful soup: Extract everything between two tags I have seen a question through the above link where we are getting the information between two tags. Whereas I need to get the information between th…

exceptions.RuntimeError - Object has no attribute errno [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 6 years ago.Improve…

How can I translate this python function to c++?

I am trying to translate a python function to c++ without success. Can someone help me? The python function receives as input a string S and 2 integers (fragment_size and jump). The aim of this functi…

Reverse PDF imposition

I have an imposed document: there are 4 n A4 pages on the n sheets. I put them into a roller image scanner and receive one 2 n paged PDF document (A3).If, say, n = 3, then Ive got the following seque…

Python: How to run flask mysqldb on Windows machine?

Ive installed the flask-mysqldb module with pip package management system on my Windows machine and I dont know how to run it.I have tried to add the path to the MySQLdb in System properties and still …

Match a pattern and save to variable using python

I have an output file containing thousands of lines of information. Every so often I find in the output file information of the following formInput Orientation: ... content ... Distance matrix (angstro…