donT use cmath

how can I write ln(x) and log(x)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
double pow(double base, int exp)
{
	if (exp == 0) return 1.;
	if (exp == 2) return base*base;
	if (exp <  0) return 1. / pow(base, -1*exp);
	if (exp %  2) return base * pow( base, exp-1 );
	return pow( pow(base, exp/2), 2);
}

double abs(double x)
{
	if (x < 0) return -1. * x;
	return x;
}

double ln(double x)
{
	double y = (x-1)/(x+1);
	double output = 1, last_val = 0;
	for (int i = 2; abs(last_val - output) > 0.000000001; i +=2)
	{
		last_val = output;
		output += pow(y, i) / ((double)i+1.);
	}
	return 2*y*output;
}

double log10(double x)
{
	return ln(x) / 2.30258509299; // ln(x)/ln(10)
}


I used an abs and pow function here, so I've provided the code for those too.
Last edited on
^ You miss a base case.
Suppose that exp=2
Whoops, you're right... Added line 4 above.
closed account (D80DSL3A)
Nice job. My 2 cents on your ln()...

You could improve efficiency by maintaining a value for y^i instead of finding it from scratch each iteration:
1
2
3
4
5
6
7
8
9
10
11
12
13
double ln(double x)
{
	double y = (x-1)/(x+1);
        double yPow = 1.0;// for accumulating a value for y^i
	double output = 1, last_val = 0;
	for (int i = 2; abs(last_val - output) > 0.000000001; i +=2)
	{               
		last_val = output;
                 yPow *= y*y;// two more factors of y here please
		output += yPow / ((double)i+1.);// replaced pow(y,i) with yPow
	}
	return 2*y*output;
}
Topic archived. No new replies allowed.