What is the algorithm used for approximating trigonometric functions in RStudio?

122 Views Asked by At

I've tried the below code on RStudio and was expecting 0, 1 and 0.5 to show up. However, it showed a very small number instead of 0 and I thought it must be using some algorithm to approximate the sin function.

sin(c(pi, pi/2, pi/6))

This was the result

1.224606e-16 1.000000e+00 5.000000e-01

I wanted to know how they approximated the sin function in this case.

1

There are 1 best solutions below

0
Ventrilocus On

Though your question may seem simple at first, the reality is quite the opposite. Whenever you want to know what a function is doing, you just have to access the function as it were an object (it literally is an object in R):

sin # function (x)  .Primitive("sin")

.Primitive is one of the ways R can call C. If you want to see the C-code, then you can use the pryr library as in:

pryr::show_c_source(.Primitive(sin(x)))
# do_math1 with op = 21

It also opens a Github page with the code of arithmetic.c, the arithmetic heart of R. R computes sin with the do_math1 function with option 21. If you want to go any further, you will need to understand how the sin function is estimated in C. For that, I recommend the following post:

How does C compute sin() and other math functions?