Skip to content

Allow for powers of big exponents #4

@alatcache

Description

@alatcache

I needed to get the power of some big numbers and found the limitations of .pow() a bit restricting. This alternative version takes advantage of the fact that given x, where 10^x = a^b, we can say x = b * log(10)a.

Anyway, thought this might help someone or lead to an enhanced .pow() function. Thanks for this great resource.

function big_pow(number,exponent) {
var nu = new Big(number);
var ex = new Big(exponent);
var ten = new Big('10');

// If the exponent is small use .pow()
if (ex.e < 3) return nu.pow(parseFloat(ex.toString()));

// Create a Big for the result
var res = new Big('1');

// Get coefficient as number
var coef_nu = parseFloat(nu.c[0] + '.' + nu.c.slice(1).join(''));

// Get coefficient's log10 value
var log_nu = Big((Math.log(coef_nu) / Math.LN10) + parseFloat(nu.e));

// Multiply by the exponent supplied
var res_exp = log_nu.times(ex);

// Get non-integer portion
var res_rem = res_exp.minus(res_exp.round(0, 0));
var f_res_rem = parseFloat(res_rem.toString());

// To the power 10 gives us the result coefficient
var res_comp = new Big(Math.pow(10,f_res_rem));

// Stuff values into the result
res.e = res_exp.round(0, 0);
res.c = res_comp.c;
return res;
}

I've done a bit of checking - but definitely supplied 'as is' ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions