0

Java float/double problem

I had this java bug/problem in Java working with float and double. I can't understand why do I get this output. https://code.sololearn.com/cLSGs4Doxc60/?ref=app If you change i from float to double, you'll get a different output. Can someone explain me this?

26th Sep 2018, 5:21 AM
Daniele Bonomi
Daniele Bonomi - avatar
3 Antworten
0
In all languages, floating numbers have a level of precision. You simply cannot store an infinite number of digits with a finite size of bytes. And you cannot print an infinite number with a finite size of bytes. That is why numeric types are defined by : -the number of bytes used for storage (the space used for each variable of this type you create) -their range (min and max number they can represent) Thus derives the precision they can achieve. You need to know that double is more precise than float (using 8 bytes vs 4 bytes, but in a larger range) : https://javarevisited.blogspot.com/2016/05/difference-between-float-and-double-in-java.html?m=1 For your problem specifically, you need to round your number (format it to print only one digit for example) so you will have the same result. Edit : and a link with the primitive types of java http://cs-fundamentals.com/java-programming/java-primitive-data-types.php Edit : lastly, people usually don't need that much precision in a program. But it is very important to aknowledge and consider when writing a program meant to compute precise/difficult/numerous operations.
26th Sep 2018, 6:02 AM
dhm
0
If you're interested in the subject, it's called propagation of uncertainty/error
26th Sep 2018, 6:09 AM
dhm
0
Thank you very much. I've been wondering about this for quite a while
26th Sep 2018, 11:56 AM
Daniele Bonomi
Daniele Bonomi - avatar