Im having a problem with a function i wrote. The idea was to calculate sin and cosin
values (operating on radians
) using taylor
expansion instead of js
math objects. These are the equations:
sin(x) = (x^1)/1! - (x^3)/3! + (x^5)/5! - (x^7)/7! + (x^9)/9! - (x^11)/11! + ...
cos(x) = (x^0)/0! - (x^2)/2! + (x^4)/4! - (x^6)/6! + (x^8)/8! - (x^10)/10! + ...
I understand that when i type something like myCos(10,2)
the result is going to be inaccurate because of low amount of iterations, however i dont understand why for (for example) x = 10
results start to be real at specifically iterNum = 6
, and becomes NaN
at iterNum = 80
. The point is that for ranges like myCos/Sin(1-40, 5-50)
(more or less) function works, but for higher numbers result becomes NaN. Not sure if my explanation is understandable, but i hope it is, just go ahead and play with the function in the console and youll see whats the problem
Here is my code:
function power(a,n) {
var result = 1;
for (var i = 0; i < n; i++) {
result = result * a;
}
return result;
}
function factorial(z) {
var result = 1;
for (var i = 1; i <= z; i++) {
result = result * i;
}
return result;
}
function mySin(x, iterNum) {
var sin = 0;
var n = 1;
for (var i = 0; i <= iterNum; i++) {
sin = sin + (power(x,n)/factorial(n) - power(x,n+2)/factorial(n+2));
n = n + 4;
}
console.log(sin + " = my function.");
console.log(Math.sin(x) + " math.sin");
}
function myCos(x, iterNum) {
var cos = 0;
var n = 0;
for (var i = 0; i <= iterNum; i++) {
cos = cos + (power(x,n)/factorial(n) - power(x,n+2)/factorial(n+2));
n = n + 4;
}
console.log(cos + " = my function.");
console.log(Math.cos(x) + " math.cos");
}