dimanche 1 octobre 2017

Adding very small and very large floating point numbers [duplicate]

This question already has an answer here:

I noticed something in my visual studio (2017) and was hoping to get some help.

I have a very small representation of a second (nanoseconds, 1.0e-9) but also a large representation of seconds (>3e10) that have passed, but when adding the two numbers together the nanoseconds disappears or is wrong.

For example:

double nanosecond = 1.0e-9;
double seconds_in_year = 31536000.0;
double result = seconds_in_year + nanosecond;

What I get for result is seconds_in_year, with no 1.0e-9. If I change nanosecond to ~5.0e-9, I get 31536000.000000004, which is off by one nanosecond.

It seems I can add very small numbers together (nano + nano) or large numbers, but when trying to combine the two it starts to go wrong. Any advice on how to work around this? I am using c++11, and cannot use external libraries like boost.

Aucun commentaire:

Enregistrer un commentaire