Search code examples
ctrigonometrycalculustaylor-series

Taylor series for arcsin(x), incorrect output C language


I wrote a program that gets from the user a value x and an integer n, the program then prints arcsin(x) using the taylor serie for arcsin http://tedmuller.us/Math/img/Taylor-arcsin.gif

but for some reason its not working. when i enter x=1 i get an output of 1.19 rather than pi/2.

here's my code:

#include <stdio.h>
#include <conio.h>
void main()
{
    int i,n;
    double x,sum,last;
    printf("Please enter the x you wish to calculate arcsin(x) for \n");
    scanf("%lf",&x);
    printf("Enter n\n");
    scanf("%d",&n);
    last=x;
    sum=last;
    for(i=1;i<=n;i++)
    {
        last*=((x*x)*(2*i-1))/((2*i)*(2*i+1));
        sum+=last;
    }
    printf("arcsin(%lf) = %lf",x,sum);
    getch();
}

basic idea is this: last and sum both start with value of x. then i advance last to be the next number in the serie, add it to sum, advance last again, add to sum...rinse and repeat n times.


Solution

  • Looks like you have a mistake in your expansion.

    Try this: last*=((x*x)*(2*i-1)*(2*i-1))/((2*i)*(2*i+1))

    You'll still need lots of terms. With 1000 terms I get arcsin(1.0) ~= 1.552963 . ( Your code 1.194958 )

    10000 terms arcsin(1.0) ~= 1.565155. ( Your code 1.194958 )