Andrey Bushman
Andrey Bushman

Reputation: 12516

Why the condition doesn't occur?

The simple C++ code:

#include "../../std_lib_facilities.h"
#include <float.h>

double ctok(double c){
    const double koef_c_2_k = 274.15;
    double k = c + koef_c_2_k;
    if(k < -koef_c_2_k) error("Output abroad range of admissible values.");
    return k;
}

int main(){
    cout << "Max double value: " << DBL_MAX << endl;
    double c = 0;
    cout << "Celsius: ";
    cin >> c;
    double k = ctok(c);
    cout << "Kelvin: " << k << endl;
    return 0;
}

Output:

bush@host-nix:~/cpp/bs/5/5.2$ ./a.out
Max double value: 1.79769e+308
Celsius: 0
Kelvin: 274.15
bush@host-nix:~/cpp/bs/5/5.2$ ./a.out
Max double value: 1.79769e+308
Celsius: 100
Kelvin: 374.15
bush@host-nix:~/cpp/bs/5/5.2$ ./a.out
Max double value: 1.79769e+308
Celsius: -100
Kelvin: 174.15
bush@host-nix:~/cpp/bs/5/5.2$ ./a.out
Max double value: 1.79769e+308
Celsius: 1.79769e+308
Kelvin: 1.79769e+308
bush@host-nix:~/cpp/bs/5/5.2$

At the last case I set the max value for the Celsius, and I have waited the error message, but I got the wrong Kelvin's value. Why it happened?

Thank you.

Upvotes: 1

Views: 222

Answers (1)

masoud
masoud

Reputation: 56519

What Every Computer Scientist Should Know About Floating-Point Arithmetic

1.79769e+308 + 274.15 seems like you're adding a cup of water to the ocean.

The precision of the real numbers is limited, and your comparison is not sensible in the computer world.

You can not use a single double variable for very small and very large numbers simultaneously. Define the range, your solution should be microscopic or macroscopic.

Upvotes: 6

Related Questions