0

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.

Phil
  • 7,287
  • 3
  • 36
  • 66
  • It's not the algorithm that's approximated, it's `pi`. It's only approximate because your computer has only finite RAM. – Hugh Nov 13 '20 at 10:52
  • @Hugh Yes `pi` is approximated but also algorithm for computing `pi` as sine is a transcendental function :-) @Hithesh See R documentation for trig functions. You'll find references – Billy34 Nov 13 '20 at 11:08

1 Answers1

0

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?

Ventrilocus
  • 1,408
  • 3
  • 13