Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overflow a float?

Working on my way to solve exercise 2.1 from "The C programming language" where one should calculate on the local machine the range of different types like char, short, int etc. but also float and double. By everything except float and double i watch for the overflow to happen and so can calculate the max/min values. However, by floats this is still not working.

So, the question is why this code prints the same value twice? I thought the second line should print inf

float f = 1.0;
printf("%f\n",FLT_MAX);
printf("%f\n",FLT_MAX + f);
like image 277
Vladimir Avatar asked Aug 22 '17 09:08

Vladimir


People also ask

Can you overflow a float?

In general, a floating point overflow occurs whenever the value being assigned to a variable is larger than the maximum possible value for that variable. Floating point overflows in MODFLOW can be a symptom of a problem with the model.

Do floats overflow in Python?

Numbers that are larger than the largest representable floating point number result in overflow, and Python handles this case by assigning the result to inf.

How do you fix a floating overflow?

The typical solution to fix this is by adding an element with clear float after the floating elements or adding a clearfix to the wrapper. But did you know you can also use the overflow property to fix this problem? It's not a new CSS trick either. It's been documented before long long ago.

What is the overflow condition in floating point numbers?

Overflow is said to occur when the true result of an arithmetic operation is finite but larger in magnitude than the largest floating point number which can be stored using the given precision.


2 Answers

Try multiplying with 10, and if will overflow. The reason it doesn't overflow is the same reason why adding a small float to an already very large float doesn't actually change the value at all - it's a floating point format, meaning the number of digits of precision is limited.

Or, adding at least that last significant digit would likely work:

float f = 3.402823e38f; // FLT_MAX
f = f +   0.000001e38f; // this should result in overflow
like image 122
Groo Avatar answered Sep 21 '22 02:09

Groo


The reason why it prints the same value twice is that 1.0 is too small to be added to FLOAT_MAX. A float has usually 24 bits for the mantissa, and 8 bits for the exponent. If you have a very large value with an exponent of 127, you would need a mantissa with at least 127 bits to be able to add 1.0.

As an example, the same problem exists with decimal (and any other) exponential values: If you have a number with 3 significant digits like 1.00*106, you can't add 1 to it because this would be 1'000'001, and this requires 6 significant digits.

You could overflow a float by doubling the value repeatedly.

like image 44
alain Avatar answered Sep 22 '22 02:09

alain