What is the definition of the natural logarithm? - Finding the value of natural logarithm using codes
Asked Answered
M

1

0

I have created an algorithm for the base of the natural logarithm with HTML and JS. And this is the code:

HTML: bonl.html

<html>
    <head>
        <title>bonl</title>
    </head>
    <body>
        <script src="bonl.js"></script>
        <input type="number" id="entered">
        <input type="button" value="run" onclick="calculate()">
        <div id="bonl">
    </body>
</html>

and Javascript: bonl.js

function calculate() {
    var x = document.getElementById('entered').value;
    console.log(x);
    var e = (1 + (1/x))**x;
    console.log(e);
    document.getElementById('bonl').innerHTML = e;
}

First, you assign a number value to <input type="number" id="entered">, and click the button named 'run'. After that, var x in bonl.js will be equal to the number assigned to 'entered'. Then, according to the definition of the base of the natural logarithm (e = lim x->inf (1+(1/x)**x)), the Javascript file will calculate the e. And the result will be displayed by <div id="bonl">.

I hope you noticed that as the value of the x gets larger, javascript file calculates the base of the natural logarithm more accurately.

However, I entered about 10 quadrillion in <input type="number" id="entered">, and I've got the result of 1 instead of 2.71828.., although I get 2.71828 when I enter 100 trillion in <input type="number" id="entered">.

Is my computer dumb to calculate e, or is there an error in my code, or is e = 1?

Masakomasan answered 8/5, 2021 at 8:56 Comment(1)
I can't be sure without setting up an environment and testing this but I believe you're running into the maximum size of a floating-point value in JavaScript. Take a look at this and see if you agree: w3schools.com/jsref/jsref_max_value.aspComplected
H
1

Yes, your computer is dumb. It can only operate floating point numbers below 2^53. When you go above that, it loses the precision and 1 + small number becomes just 1:

for (let pow = 1; pow < 60; pow++) {
    let n = 2 ** pow;
    console.log('2^', pow, 'small=', 1 + 1/n, 'e=', (1 + 1/n)**n)
}

Can we do better than that? Yes, we can! Instead of computing e using floating point numbers, let's compute some_big_number * e using Big Integers, which, unlike floats, have unlimited precision. Using BigInts we can compute as many terms of the power series as we want:

let BIG = 10n ** 100n

let f = 1n
let e = BIG
let n = 1n


while (1) {
    f = f * n
    let eNext = e + BIG / f
    if (eNext === e) {
        document.write(`e = ${e} <br>`)
        document.write(`terms = ${n} <br>`)
        break
    }
    e = eNext
    n += 1n
}
Habitue answered 8/5, 2021 at 9:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.