1

I am trying calculate the following series in JavaScript:

enter image description here

My code is as follows:

var res = []
for(var i=0; i<1000; i++) {
    res.push(i / ((i * Math.sqrt(i + 1)) + ((i + 1) * Math.sqrt(i))))
}

But this makes the series possibly converge towards 0 rather than approach 1. Here's the first 150 steps:

enter image description here

Is there something wrong with my translation from math to JavaScript? Maybe my parentheses?

UPDATE

As per @Barmar 's answer, the correct code shows convergence to 1 only for small values of infinity, diverging after 4 steps:

enter image description here

Cybernetic
  • 12,628
  • 16
  • 93
  • 132

1 Answers1

1

You need to add each element of the series to the previous sum.

You also need to start at i = 1 to avoid dividing by 0.

console.config({
  maxEntries: Infinity
});

var res = [];
var sum = 0;
for (var i = 1; i < 1000; i++) {
  sum += i / ((i * Math.sqrt(i + 1)) + ((i + 1) * Math.sqrt(i)));
  res.push(sum);
}
console.log(res);
.as-console-wrapper {
  max-height: 100% !important;
}

Note that this shows that the series doesn't actually converge to 1. Which is also apparent from your incorrect graph, since you can see that the first 5 elements are between 0.195 and 0.293, and these add up to more than 1.

Barmar
  • 741,623
  • 53
  • 500
  • 612