Python representation of floating point numbers [duplicate]
2024/11/15 23:25:09
I spent an hour today trying to figure out why
return abs(val-desired) <= 0.1
was occasionally returning False, despite val and desired having an absolute difference of <=0.1. After some debugging, I found out that -13.2 + 13.3 = 0.10000000000000142. Now I understand that CPUs cannot easily represent most real numbers, but this is an exception, because you can subtract 0.00000000000000142 and get 0.1, so it can be represented in Python.
I am running Python 2.7 on Intel Core architecture CPUs (this is all I have been able to test it on). I'm curious to know how I can store a value of 0.1 despite not being able to apply arithmetic to particular floating point values. val and desired are float values.
All these numbers can be represented with some 16 digits of accuracy. So why:
>>> 13.3-13.2
0.10000000000000142
Why only 14 digits of accuracy in that case?
Well, that's because 13.3 and -13.2 have 16 digits of accuracy, which means 14 decimal points, since there are two digits before the decimal point. So the result also have 14 decimal points of accuracy. Even though the computer can represent numbers with 16 digits.
If we make the numbers bigger, the accuracy of the result decreases further:
I have following python dictionary.a={name:test,age:26,place:world,name:test1}How to grep only duplicate key:value pair from the above?Output should be: "name: test and name:test1"
This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 7 months ago.I get the IndentationError: expected an indented block.
I was tryi…
I created a DataFrame and I am trying to sort it based on the columns. I used the below code.frame.sort_index(axis=1)But this is causing the below errors------------------------------------------------…
This is probably a simple fix, but having a little trouble getting my head around it; Im reading lines from a different script, and want to replace a line with a variable, however it replaces it with b…
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 10 years ago.Improv…
I have a string on unknown length, contain the characters a-z A-Z 0-9. I need to change each character using their position from Left to Right using a dictionary.Example:string = "aaaaaaaa"
d…
If I do this, I get:>>> x = 1
>>> y = 2
>>> type(x)
<class int>
>>> type(y)
<class str>That all makes sense to me, except that if I convert using:>>…
I am new to python and I want to write a program that asks for a line of input (each number will be separated by a single space.) It would use a simple letter-number substitution cipher. Each letter w…