using a riemann sum, compute the value of ln(5.6), using the definition of the ln function as an integral. compare your result with the true value of ln(5.6) in javascript

The function ln(x) is defined as the integral of 1/t from 1 to x:

index.tsx
ln(x) = integral from 1 to x of dt/t
37 chars
2 lines

We can approximate this integral using a Riemann sum. Let delta_x be the width of each rectangle and let x_i = 1+i*delta_x be the right endpoint of the i-th rectangle. Then, our approximation of ln(x) is:

index.tsx
ln(x) ~ sum from i=0 to n-1 of delta_x/x_i
43 chars
2 lines

We can implement this in JavaScript as follows:

index.tsx
function ln(x, n=1000) {
  const delta_x = x/n;
  let sum = 0;
  for (let i = 1; i <= n; i++) {
    const x_i = delta_x * i;
    sum += delta_x / x_i;
  }
  return sum;
}
171 chars
10 lines

Now, we can compare our approximation with the true value of ln(5.6):

index.tsx
const approx = ln(5.6);
const trueValue = Math.log(5.6);
console.log("Approximation: ", approx); // Output: Approximation: 1.7226421149831872
console.log("True Value: ", trueValue); // Output: True Value: 1.722766597741001
223 chars
5 lines

As we can see, our approximation is very close to the true value of ln(5.6).

related categories

gistlibby LogSnag