Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does double type return Infinity?

Tags:

c++

I made this code in C++ just to check the biggest integer int and double data types can store.

#include<iostream>
using namespace std;
int main() {
    int a, b;
    cin >> a;
    b = a;
    for(int c; a > 1; a = a * b)
        cout << a << "\n";
};

When I input 2 in the code below, the biggest integer printed is 1073741824.

I changed the code to:

#include<iostream>

using namespace std;

double main() {
    double a, b;
    cin >> a;
    b = a;
    for(double c; a > 1; a = a * b)
        cout << a << "\n";
};

The output of the second code quickly from 2 to printing infinity. Why doesn't the code stop at the largest value of double? Why does it stop in the previous code?

like image 602
Lalit Kumar Avatar asked Jul 22 '26 02:07

Lalit Kumar


2 Answers

The behaviour on overflowing an int is undefined. Because of this it is not possible to elucidate the maximum possible value that can be stored in an int. So we have to rely on a constant that your platform will provide for you: std::numeric_limits<int>::max() is the value of the largest int.

For the double case, technically the behaviour is also undefined. Although if your platform implements IEEE754, then +Inf will eventually be attained by repeated multiplication of a large enough value; a little over 11. The largest double that isn't +Inf that your platform supports is std::numeric_limits<double>::max().

Finally, main is not allowed to return anything other than an int. Didn't your compiler warn you of that?


1 The actual value of "a little" is std::numeric<double>::epsilon(). Acknowledge @YSC.

like image 200
Bathsheba Avatar answered Jul 24 '26 17:07

Bathsheba


I made this code in C++ just to check the biggest integer int and double data types can store

This is how you get the largest value you can store in a data type:

#include <iostream>
#include <limits>
using namespace std; // not in real code plz

int main() {
    cout << "largest int is " << numeric_limits<int>::max() << '\n';
    cout << "largest double is " << numeric_limits<double>::max() << '\n';
    return 0;
}

Your trial multiplication wouldn't get this right even if it was well-defined: it would just show you the last value of a such that the real maximum is between a and a*b.

like image 35
Useless Avatar answered Jul 24 '26 17:07

Useless