Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis+ 3
Sololearn python bug? š¤Ø
There is a wierd bug(?) that wasn't allowing me to finish simple task. If i multiply simple number for example: 4000, 50, 49, 40, by 1.1 I expect to get results like: 4400.0, 55.0, 53.9, 44.0 However I get results like 4400.0, 55.000000000001, 53.900000000006, 44.0 It wouldn't be that confusing if it wouldn't be random Try it yourself: print(4000*1.1) print(50*1.1) print(49*1.1) print(40*1.1)
6 Respostas
+ 7
Piotr Å ,
what we can do depends a bit on what we are going to do with these results.
āŖļøif it is just to output the number with a specific number of decimal places, we can use print() with f-string that can format the output. the numbers itself keeps as they are, but the output is according the arguments that are used with f-string
āŖļøif we need these numbers for mathematical or comparison operations, we can use round() function which creates new numbers that are rounded to the specific number of decimal places.
āŖļøfor high precision calculations we can use the decimal module of python, that provides support for fast correctly-rounded decimal floating point arithmetic
an other way of doing the calculation can also help:
print(49*1.1, 49 * 110 /100) => results in: 53.900000000000006 53.9
.
+ 5
Not only Sololearn code playground, It will give you the same output in any ide.
https://stackoverflow.com/questions/588004/is-floating-point-math-broken
+ 5
Oh I see, thank you Simba, anyway how do you deal with it? In my example I had to compare two numbers by == or > etc, so this bug messed it all. Finally I just added round(x,2) to round particular part, but it feels insane to add it to all floats" just in case".
+ 2
Shubham Bhatia good ššbut who asked š¤£š¤£š¤£šš
+ 1
Oh thank you Lothar this is indeed a great reply:
*110/100, instead *1.1 seems to fix it :)
It's really great to have so friendly and knowledgeable community.
0
I like sololearn Coding šŖ playground. šÆ