ATW
ATW

Reputation: 289

C++: Implementing a numeric approximation for ln(a)

I want to implement the formula:

enter image description here

#include <iostream>
#include <cmath>
#include <limits>

using namespace std;

int main(){
    double a, eps = numeric_limits<double>::epsilon();
    cout << "a=";
    cin >> a;
    double w = sqrt(a), prod = 1 + w;
    int n = 1;
    do {
        w = sqrt(w);
        prod *= 1 + w;
        cout << "ln(" << a << ")=" << ldexp(a-1, n)/prod << endl;
        n++;
    } while(abs(w - 1) > eps);

    return 0;
}

But e.g. ln(2.78787)=0.512639 and that cannot be true. Where is the mistake?

Upvotes: 3

Views: 165

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52601

Initial conditions for the loop are off. Start with

double w = a, prod = 1;

and the program would produce expected results

Upvotes: 4

Related Questions