0

I have a homework in C. We have to write our own asin() function with Taylor method, and we can't use math.h

It works fine, but once I put higher count of iterations(int i), it returns NaN(Not a Number), and when I use low count of i, the number is not exact. Can anyone help me with this?

double my_asin(double x)
{
    int i = 0;
    double vypocet = x;
    double y = vypocet;
    for(i=1;i<=10000;i++)
    {
        vypocet*=((x*x)*(2*i-1)*(2*i-1))/((2*i)*(2*i+1));
        y+=vypocet;

    }
    printf("my_asin = %.10e\n", y);
    return y;
}

EDIT: Thank you all! finished it :)

user3021851
  • 131
  • 1
  • 8
  • Your homework assignment was *not* to teach you how to write an asin() function, pointless with an asin() function available in math.h. It was to teach you how floating point math can be inaccurate and how it can misbehave. Now you know. – Hans Passant Nov 23 '13 at 13:14
  • 2
    could you post some results (expected and wrong ones) for some input value and some iteration count? – rano Nov 23 '13 at 13:15
  • See also this (case #3) http://stackoverflow.com/questions/19086471/matlab-code-glitch-at-the-end/19088125#19088125 -- when you add more iterations, both the nominator and the denominator of Taylor series approach Infinity; when divided by itself, the result is NaN. As a matter of fact, you should learn how to cancel this kind of mistake. – Aki Suihkonen Nov 23 '13 at 15:51

1 Answers1

0

Two things are required for your answer :

  1. Regarding maths : The series expansion you are coding is a sin inverse (arcsin) and expecting an output in radian.

    sin^(-1)x=x+1/6x^3+3/(40)x^5+5/(112)x^7+(35)/(1152)x^9+... . As you can see this is an expansion which is monotonically increasing and expecting value (input) between [-1,1] only. When you plug in large values e.g. 10 you are bound to get results you don't expect.So , plug in correct values. I guess, put correct values [-1,1] when calling the function my_asin() and your code would work fine FOR THE number of ITERATIONS YOU HAVE NOW.

    e.g 1.5146343691e+000 looks fine for 90 degrees or pi/2 or my_asin(1).

    2 .Regarding Floating Point (double i.e. single prrecision floating point ):They cant represent all the numbers on the real line, their range is a subset of R.And when there is a number that can't be represented correctly by their 32 bits encoding (IEEE 754) you will get error in result. Number as simple as 0.1 cant be represented exactly using floating point.

    Check these pages for FP Errors and FP Exceptions :

  2. http://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html
  3. http://www.gnu.org/software/libc/manual/html_node/FP-Exceptions.html#FP-Exceptions
Rafed Nole
  • 112
  • 1
  • 4
  • 16