1

so I created a program that takes in two long double numbers and some a particular form of calculation on them. but the issue is, the output for me is inf or in some compilers, 0.. So the error only occurs when I enter exponential values like say I enter 1.11224e+2121 1.11224e+2121 then I get inf or 0 but if I get something like 2.4 5.9 I get proper value. How do I fix this?

here is my code

#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

int main()
{
    long double a,b,add=0,mean=0;
    cin>>a>>b;
    vector<long double> vector;
    vector.push_back(a);
    vector.push_back(b);
    mean=(vector[0]+vector[1])/2;
    for (int k = 0; k < 2; k++)
    {
        add= add+ pow((vector[k] - mean), 2);
    }
    cout<<add/2;

    return 0;
}
Jim Kelly
  • 11
  • 3
  • 1
    each type of variable says `double, int, long ...` have limited capacity to store data. you need to decide your input range and choose proper type accordingly. the type `unsigned long long` is the STL variable that accepts the largest number in C++. if you want something bigger, you need to use external `Big int` types. – prhmma Dec 01 '19 at 07:29
  • 1
    Please check the value of `std::numeric_limits::max()`. The value of `1.11224e+2121` (111224 followed by 2116 zeros) seems extremely large. I believe that the limit is around `1.7e+308` (17 followed by 307 zeros). Just to depict how large your value is, if you subtract `1.7e+308` from `1.11224e+2121`, you get approximately... `1.11224e+2121` (the same!!!). – goodvibration Dec 01 '19 at 07:33
  • 2
    Very few real-world implementations have a `long double` that can represent values anywhere near as large as `1.11224e+2121`. That will overflow. Then all bets are off for subsequent calculations. – Peter Dec 01 '19 at 07:52
  • 1
    if you're on gcc then the option `-mlong-double-128` may help in this situation, with a much worse performance. On x86 you can also use `-mlong-double-80`. But you still need to decide which range of numbers you want, since they're still not types with infinite precision – phuclv Dec 01 '19 at 09:07
  • @Evg yes, I've already edited my comment long ago – phuclv Dec 01 '19 at 09:16

0 Answers0