Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should you ever use a float instead of a double? [duplicate]

Tags:

c++

I'm pretty new to coding, so this might be a stupid question, but why should you ever use a float when a double is more precise and has more bits?

like image 363
Damna Liana Avatar asked Oct 19 '25 10:10

Damna Liana


1 Answers

Memory

The biggest reason is memory space. A float takes up 32 bits (4 bytes) while a double takes up 64 bits (8 bytes). This may not seem like a big deal, but some applications deal with a lot of numbers.

Let's say I'm simulating some system with a 3D grid that is a cube of values with a width of 1,000 points. That's 1,000,000,000 data points. If each point is a float value, I need 4 GB of memory. For doubles, I need 8 GB of memory. If I need to store more than one value at each point in the grid, the memory requirements just get bigger.

Grids similar to what I just described can be useful in physical simulations (climate or weather models, certain fluid dynamics simulations, etc). In those types of simulations, adding twice as many points can often be more useful than adding twice the precision at each point.

Speed

Depending on the hardware, the speed of calculation might also be a factor for time-sensitive calculations, but which is better depends on the underlying hardware. (See this answer for more details on that: https://stackoverflow.com/a/4584707/5941564)

If you are developing real-time software for a very specific piece of hardware that handles float faster than doubles, you should favor floats. But, some processors handle doubles faster, so you need to know your hardware before making that kind of performance decision.

like image 97
Kyle A Avatar answered Oct 22 '25 02:10

Kyle A