NathanOliver
Posting Virtuoso
1,516 posts since Apr 2009
Reputation Points: 281
Solved Threads: 278
Skill Endorsements: 3
I am facing problem using float
in loop its value stuck at 8388608.00
First read up a bit on the representation of floating point numbers and loss of precision.
http://www.cprogramming.com/tutorial/floating_point/understanding_floating_point_representation.html
Then, try out this program:
#include <limits>
#include <iostream>
#include <iomanip>
int main()
{
typedef std::numeric_limits<float> limits ;
std::cout << "exponent ranges from: " << limits::min_exponent << " to "
<< limits::max_exponent << " binary ie. about "
<< limits::min_exponent10 << " to " << limits::max_exponent10
<< " decimal\nmantissa has " << limits::digits << " binary digits "
<< "ie. about " << limits::digits10 << " decimal digits\n" ;
const unsigned long long max_mantissa = ( 1U << (limits::digits-1) ) - 1 ;
std::cout << std::fixed << std::setprecision(limits::digits10)
<< "max value of normalised mantissa: " << max_mantissa << '\n' ;
float big = max_mantissa ;
float small = 0.1 ;
float a = big, b = small, c = -a ;
std::cout << "a == " << a << '\n' ;
std::cout << "b == " << b << '\n' ;
std::cout << "a+b == " << a+b << '\n' ;
std::cout << "a-b == " << a-b << '\n' ;
std::cout << "a+b+c == " << a+b+c << '\n' ;
std::cout << "a+c+b == " << a+c+b << '\n' ;
}
Can you explain the output?
This is the output on my implementation:
exponent ranges from: -125 to 128 binary ie. about -37 to 38 decimal
mantissa has 24 binary digits ie. about 6 decimal digits
max value of normalised mantissa: 8388607
a == 8388607.000000
b == 0.100000
a+b == 8388607.000000
a-b == 8388607.000000
a+b+c == 0.000000
a+c+b == 0.100000
vijayan121
Posting Virtuoso
1,740 posts since Dec 2006
Reputation Points: 1,236
Solved Threads: 320
Skill Endorsements: 11