Show Float Imprecision

I am supposed to write code that will show that if you square root a number and get an irrational result, then square that result that the result won't be the original value because of the imprecise nature of the float value. The trouble is...I haven't been able to reproduce that, in the following code numberToSqrRt ends up having the same value as result.

1
2
3
4
 33      float numberToSqrRt = 7919;
 34      float theSquareRoot = sqrt(numberToSqrRt);
 35      float result  = numberToSqrRt * numberToSqrRt;
 36      cout << result << endl;


This is supposed to be fairly simple, the 7th program we're supposed to write. I can use setprecision to get the desired results, but I'm not expected to. Can anyone see what I am doing wrong?
33
34
35
36
37
38
39
     float numberToSqrRt = 7919.0f; // I always fully specify a FP number 
     float theSquareRoot = std::sqrt(numberToSqrRt); // the std version takes various types

     float result  = numberToSqrRt * numberToSqrRt;
     float result  = theSquareRoot * theSquareRoot; // use the correct variable

     cout << result << endl;


The use of the f on line 33 helps prevent unnecessary implicit casting: 7919 is an int, 7919.0 is a double, 7919.0f is a float.

Hope this helps.
Hey thank you for the suggestion, I had high hopes for it, unfortunately I'm still getting the same result :/
I am lazy - can you post all of your code, so I can paste it into my IDE - hopefully no line numbers!!
Or PM it to me if you don't want it to be public.
Did you try calculating the discrepancy between the result and the original number?
1
2
3
4
5
    float numberToSqrRt = 7919.0f;
    float theSquareRoot = sqrt(numberToSqrRt);
    float result  = theSquareRoot * theSquareRoot;
    float difference = numberToSqrRt - result;
    cout << result << "  " << difference << endl;
Try adding this - it worked for me.



1
2
3
4
5
#include <iomanip>

std::cout << std::fixed;



7918.999512

Last edited on
Topic archived. No new replies allowed.