Please help, I have tried and tried to make this work like my teacher wants it to work.
I am suppose to write code to find the square root of a number using the Taylor Series, which is:
sqrt(x) = 1 + 1/2(x-1) -
1/4(x-1)^2/2! + 3/8(x-1)^3/3! - 15/16(x-1)^4/4!
This way works.
CODE
#include <stdio.h>
#include <math.h>
int main(void)
{
double x, n, m = 0.0;
int i, cnt = 0;
// Any input
printf("Enter a number.\n");
scanf("%lf", &n);
x = n;
m = sqrt(n);
// Divide by 4 until n < 1
while (n > 1) {
n = n/4;
cnt++;
}
double mysqrt;
double x1, x2, x3, x4, x5;
x1 = 1.0;
x2 = (n-1)/2;
x3 = x2*(n-1)/4;
x4 = x3*(3/8)*(n-1)/(3*2);
x5 = x4*(15/16)*(n-1)/(4*3*2);
mysqrt = x1 + x2 - x3 + x4 - x5;
// Add up the pieces
float total, xx;
xx = pow (2,cnt);
total = mysqrt * xx;
printf("Library function, the square root of %.3lf is %.3lf\n", x, m);
printf("Talor Series, the square root of %.3lf is %.3lf\n", x, total);
return 0;
}
But my teacher wants me to use this form.
// sqrt(1-x) = 1 - x/2 - x^2/4 -
.... - {1*3*5...(2n-3)x^n/2*n*n!
Mine does not work
CODE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
double x, n, m = 0.0;
int i, cnt = 0;
// Any input
printf("Enter a number.\n");
scanf("%lf", &n);
x = n;
m = sqrt(n);
// Divide by 4 until n < 1
while (n > 1) {
n = n/4;
cnt++;
}
double mysqrt = 1.0;
double x1 = 1;
for (i=1; i<=5; i++) {
x1 = 1 * (((2 * i) - 3) * (1-n)) / (2 * i * i);
mysqrt = mysqrt + x1;
}
// Add up the pieces
if (cnt)
mysqrt = (cnt * 2) * mysqrt;
printf("Library function, the square root of %.3lf is %.3lf\n", x, m);
printf("Talor Series, the square root of %.3lf is %.3lf\n", x, mysqrt);
return 0;
}
This post has been edited by NickDMax: 23 Nov, 2007 - 04:29 PM