Skip to main content

Float vs Double ... I found a problem

4 replies [Last post]
mcvillarp
Offline
Joined: 2008-01-28

I'm learning Java, and guessing that float arithmetic is faster than double arithmetic, I made a simple program: to sum 10,000,000 times 3

I found that double is faster than float ... but I forgot that when, with double I got 3.0E7, the correct result and with float I got 3.4407592E7 .... ¿What is happening?

Testing, the problem starts at 5,592,409 ... very far from 3.4028235E38

I can't find my mistake ... please, help me to understand.

Code (I omitted the time instructions and logic trying to focus mi problem):

public class ErrorFloat {

public static void datoFloat(int limite){
float suma=0.0f;

for (int i=0;i

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
swv
Offline
Joined: 2007-05-28

linuxhippy said:
Microbenchmarks (simply do things some millions of time and measure their duration) don't work with java.

why not? I think they can if you take into account class loading overhead. You say no?

linuxhippy
Offline
Joined: 2004-01-07

> why not? I think they can if you take into account
> class loading overhead. You say no?

His intention was to measure wether float is faster tha double.
For such an investigation I doubt that you would like to have class-loading + interpreted-execution + (on uniprocessor systems) costs of compilation in your benchmarking results?

lg Clemens

linuxhippy
Offline
Joined: 2004-01-07

1.) Microbenchmarks (simply do things some millions of time and measure their duration) don't work with java.

2.) Float has less precision than double, and float/double are floating point formats, so ... while the "double" result seems to be right and the float one seems to be "wrong", both are wrong - but float is more wrong than double. I would really recommend reading artuicles how floating point values work, if you don't understand them, you'll make mistakes.

3.) Modern desktop processors don't have problems with float/doubles and process both equal fast.

lg Clemens

mcvillarp
Offline
Joined: 2008-01-28

Thanks for your tips 1 and 3. It was an idea to talk about with my students, but I trust in your experience.

I know how floating point values work, I know about IEEE754... wait, I have an idea.

I have made a C program and I got the same results ... I can't believe that error with a relative "small" number.

Ok ... I need to study deeper floating point values and arithmetic.

Thanks,