Hi,
GeoGrebra, C++ and C# all agree about what cosh(16.612) should be. But when I use a function I wrote myself, which uses an algorithm to calculate the hyperbolic cosine, I get a (very slightly) different result. I've tried setting Visual Studio's floating point handling to precise, strict and fast, but to no avail.
What could the proble be?
This is the one that everyone else agrees about:
cosh(16.612000) = 8193509.0494933873414993
This is my first approach:
_cosh(16.612000) = 8193509.0494933854788542
And my second:
ecosh(16.612000) = 8193509.0494933798909187
The last one uses cosh(x) = 0.5(e^x + e^(-x))
Here is my code:
#include <cstdio>
#include <iostream>
#include <string>
long double e = 2.718281828459045090795598298427648842334747314453125L;
long double ecosh(long double x) {
return 0.5L * (pow(e, x) + pow(e, -x));
}
using namespace std;
using decimal = double;
constexpr bool b(int i) { return i > 0; }
static_assert(b(7), "hej");
auto f = [=](double x) {
return sqrt(x*x*x);
};
long double fac(long double x) {
if ((int)x > 1)
return x * fac(x - 1);
return 1;
}
decimal _sqrt(decimal x, int iterations = 15) {
decimal y = x - x / 2 + x / 4;
for (int i = 1; i < 49; i++) {
y += x / pow(2, i) * 1.5 * pow(-1, i);
}
return y+0.0000000001;
}
long double _cosh2(double x) {
long double y = 0;
for (int i = 1; i < 70; i++) {
y += pow(x, (double)(2.0*i)) / fac(2.0*i);
}
return y+1;
}
long double _sinh2(double x) {
long double y = x;
for (int i = 1; i < 70; i++) {
y += pow(x, (double)(2.0*i+1)) / fac(2.0*i+1);
}
return y + 0;
}
int main(int argc, char** argv)
{
double r = 4.0;
printf("sqrt(%f) = %.25f\n\n", r, _sqrt(r));
printf("sqrt(%f) = %.25f\n\n", r, sqrt(r));
double d = 16.612;
printf("_cosh(%f) = %.16f\n cosh(%f) = %.16f\n", d, _cosh2(d), d, cosh(d));
printf("ecosh(%f) = %.16lf\n", d, ecosh(d));
printf("--------------------------------------\n");
printf("e() = %.75lf\ne = %.75f\n", exp(1.0L), e);
printf(" %.50f\n", _sinh2(6.125));
printf(" %.50f\n", sinh(6.125));
getchar();
}
What I have tried:
I've tried reconfiguring Visual Studio 2017.