1

I try to write a simple integral for sin(x) function. Normally integral of sin(x) from 0, to pi equals to 2, but my js code gives me 114. what is problem with my code?

let i = 0
let total = 0;
for(i=0; i<=180; i++ ) {
    total += Math.sin(i*(Math.PI/180))
}
console.log(total)
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
Hakan Egne
  • 11
  • 1
  • 3
    Integral of sin(x) is -cos(x) – kelsny Nov 01 '22 at 20:24
  • 3
    If you think of this as a sum of rectangles, then you correctly determine that the _height_ of each rectangle is `Math.sin(i * (Math.PI / 180))`, but you forgot to consider the _width_ of each rectangle; it’s not `1`. You’re subdividing `Math.PI` into 180 parts, so you have to multiply each term by `(Math.PI / 180)`. The result is `1.9999492301722783`. Actually, you’re counting 181 parts; the loop condition should be `i < 180`. – Sebastian Simon Nov 01 '22 at 20:29

1 Answers1

1

Taking @SebastianSimon's comment, we find:

If you think of this as a sum of rectangles, then you correctly determine that the height of each rectangle is Math.sin(i * (Math.PI / 180)), but you forgot to consider the width of each rectangle - which is not 1. You’re subdividing Math.PI into 180 parts, so you have to multiply each term by Math.PI / 180.

let total = 0;

for (let i = 0; i < 180; i++) { // i < 180, not i <= 180
    total += Math.sin(i * (Math.PI / 180)) * (Math.PI / 180);
    //                                        ^^^^^^^^^^^^^ width of each rectangle
    //       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ height of each rectangle
}

console.log(total); // VERY CLOSE to 2

However, you'll notice that the end result is not exactly equal to 2, but very close to it. This is because of floating point arithmetic; see this question for a detailed explanation.

kelsny
  • 23,009
  • 3
  • 19
  • 48
  • 1
    Well, almost all of the numeric error comes from the low approximation of 180 subdivisions. – Sebastian Simon Nov 01 '22 at 20:38
  • We general use https://stackoverflow.com/questions/588004/is-floating-point-math-broken as the link for floating point issues, to keep it inside the site. – Barmar Nov 01 '22 at 20:42