John Theodore Yap
John Theodore Yap

Reputation: 1

Trying to find the ln or natural logarithm of numbers

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;
}

Upvotes: 0

Views: 3562

Answers (1)

Null
Null

Reputation: 1970

If you simply want to compute the natural logarithm of a number you can use std::log. To compute the logarithm with any base you can write a function like this:

double log(double base, double x) {
  return std::log(x)/std::log(base);
}

You would need to add code to check for valid inputs (e.g. base cannot be equal to 1 or less than 0).

If you want to implement the natural log without std::log you might want to take a look at std::numeric_limits for your difference limit instead of hard coding it to lim = 0.000001.

Upvotes: 2

Related Questions