Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of type "long double" with GCC and C++11

Tags:

c++

double

I've tried searching for information on long double, and so far I understand it is implemented differently by compilers.

When using GCC on Ubuntu (XUbuntu) Linux 12.10 I get this:

double PId = acos(-1);
long double PIl = acos(-1);
std::cout.precision(100);

std::cout << "PId " << sizeof(double) << " : " << PId << std::endl;
std::cout << "PIl " << sizeof(long double)  << " : " << PIl << std::endl;

Output:

PId 8  : 3.141592653589793115997963468544185161590576171875
PIl 16 : 3.141592653589793115997963468544185161590576171875

Anyone understand why they output (almost) the same thing?

like image 534
FreelanceConsultant Avatar asked Dec 16 '12 17:12

FreelanceConsultant


1 Answers

According to the reference of acos, it will return a long double only if you pass a long double to it. You'll also have to use std::acos like baboon suggested. This works for me:

#include <cmath>
#include <iostream>

int main() {

  double PId = acos((double)-1);
  long double PIl = std::acos(-1.0l);
  std::cout.precision(100);

  std::cout << "PId " << sizeof(double) << " :  " << PId << std::endl;
  std::cout << "PIl " << sizeof(long double)  << " : " << PIl << std::endl;
}

Output:

PId 8  : 3.141592653589793115997963468544185161590576171875
PIl 12 : 3.14159265358979323851280895940618620443274267017841339111328125

         3.14159265358979323846264338327950288419716939937510582097494459

The last line is not part of the output and contains the correct digits for pi to this precision.

like image 133
schnaader Avatar answered Sep 30 '22 18:09

schnaader