The recursive result of JS factorial tail is abnormal.

// 
function factorial1(n,total) {
    if (n === 1) {
        return total;
    }
    return factorial1(n - 1, n * total);
}

// 
function factorial2(n) {
    if (n === 1) {
        return 1;
    }
    return n * factorial2(n - 1);
}

console.log(factorial1(25,1)); // 1.5511210043330984e+25 
console.log(factorial2(25)); // 1.5511210043330986e+25

when the value of n is relatively large, such as 25, the result begins to be abnormal, and the result calculated by non-tail recursion is correct.
what"s wrong with this?

Mar.25,2021

the numerical value in the calculation is too large, which leads to the overflow of the numerical type, and the calculation of large numbers is repeated in the ordinary recursive way. if there are more steps for the loss of accuracy caused by the overflow, it is different from method 1, and the error in the calculation is method 2

.

reference:
https://stackoverflow.com/que.

Menu