loge(a) takes a which is a nonzero positive real number.
In the function, x = a/3. y = x-1+a*exp(-x). I will continue to subtract them from each other (get absolute difference) and continue until the difference is less than 0.000001. My friends tell me what I'm doing is correct, but when I try loge(2), I get 0.678(something). Anything higher causes it to seg fault. Any tips? Thanks.
#include <iostream>
using namespace std;
long double power(long double a, long int b);
long double power(long double a, long int b)
{
if (b == 0)
{
return 1;
}
else if (b == 1)
{
return a;
}
else if (b < 0)
{
return 1.0/power(a, -b);
}
else if (b%2==0)
{
return power(a*a, b/2);
}
else if (b%2!=0)
{
return a*power(a*a, b/2);
}
}
long double exp(long double x);
long double exp(long double x)
{
if (x < 0.000001)
{
return 1+x+(power(x, 2)/2)+(power(x, 3)/6);
}
else
{
return power(exp(x/10), 10);
}
}
long double loge(long double a);
long double loge(long double a)
{
long double x, y, lim = 0.000001;
if (a == 1)
{
return 0;
}
else
{
x = a/3;
y = x-1+a*exp(-x);
while (x*lim != y*lim)
{
x = y;
y = x-1+a*exp(-x);
}
return y;
}
}
int main()
{
long double num;
cout << "Enter a number: ";
cin >> num;
cout << loge(num);
cout << "\n";
return 0;
}