Re: Can someone please tell me where I am going wrong??



E-Dot wrote:

I am trying to write a program which asks the user to enter a number
in the interval [1,2], the program then gives the natural logarithm of
that number, using the series for log(x+1)...

Here is what I have so far and can't figure out what i'm doing wrong.
any help would be greatly appreciated, thanks guys...

#include <stdio.h>
#include <math.h>

int main() {

int i,n;
double x;
float sum, term;

printf("Enter a number in the interval [1,2]> ");
scanf("%d", &x);

sum = 0;
i = 0;

do {
i = i+1;
x = (double) i;
term = pow(x, i)/i;
if(i % 2 == 1)
sum = sum + term;
else
sum = sum - term;

} while(i <= n);

printf("The answer is %lf\n",sum);

/* BEGIN new.c */

#include <stdio.h>
#include <float.h>

double fs_log(double x);
double fs_sqrt(double x);

int main(void)
{
double x, e;

fputs("Enter a number in the interval [1,2]> ", stdout);
fflush(stdout);
if (scanf("%lf", &x) == 1) {
e = fs_log(x);
printf("The answer is %f\n", e);
} else {
puts("scanf(\"%lf\", &x) != 1");
}
return 0;
}

double fs_log(double x)
{
int n;
double a, b, c, epsilon;
static double A, B, C;
static int initialized;

if (x > 0 && DBL_MAX >= x) {
if (!initialized) {
initialized = 1;
A = fs_sqrt(2);
B = A / 2;
C = fs_log(A);
}
for (n = 0; x > A; x /= 2) {
++n;
}
while (B > x) {
--n;
x *= 2;
}
a = (x - 1) / (x + 1);
x = C * n + a;
c = a * a;
n = 1;
epsilon = DBL_EPSILON * x;
if (0 > a) {
if (epsilon > 0) {
epsilon = -epsilon;
}
do {
n += 2;
a *= c;
b = a / n;
x += b;
} while (epsilon > b);
} else {
if (0 > epsilon) {
epsilon = -epsilon;
}
do {
n += 2;
a *= c;
b = a / n;
x += b;
} while (b > epsilon);
}
x *= 2;
} else {
x = -DBL_MAX;
}
return x;
}

double fs_sqrt(double x)
{
int n;
double a, b;

if (x > 0 && DBL_MAX >= x) {
for (n = 0; x > 2; x /= 4) {
++n;
}
while (0.5 > x) {
--n;
x *= 4;
}
a = x;
b = (1 + x) / 2;
do {
x = b;
b = (a / b + b) / 2;
} while (x > b);
while (n > 0) {
x *= 2;
--n;
}
while (0 > n) {
x /= 2;
++n;
}
} else {
if (x != 0) {
x = DBL_MAX;
}
}
return x;
}

/* END new.c */

--
pete
.



Relevant Pages