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.