Heres a nice algorithm for positive integer powers, it starts by dealing with some simple cases and then uses a loop testing the binary bits of the exponent. For example to find 3^11 11 in binary is 1011 so the stages in the loop are

  • bitMask = 1011, evenPower = 3, result = 3
  • bitMask = 101, evenPower = 3*3 = 9, result = 3*9 = 27
  • bitMask = 10, evenPower = 9*9 = 81, result = 27
  • bitMask = 1, evenPower = 81*81 = 6561, result = 27*6561 = 177147

That is the evenPower squares at each loop, and the result gets multiplied by the evenPower if the bottom bit is 1. The code has been lifted from Patricia Shanahan’s method http://mindprod.com/jgloss/power.html which in turn has its roots in Kunth and can be traced back to 200 BC in india.

/**
 * A fast routine for computing integer powers.
 * Code adapted from {@link <a href="http://mindprod.com/jgloss/power.html">efficient power</a>} by Patricia Shanahan [email protected]
 * Almost identical to the method Knuth gives on page 462 of The Art of Computer Programming Volume 2 Seminumerical Algorithms.
 * @param l number to be taken to a power.
 * @param n power to take x to. 0 <= n <= Integer.MAX_VALUE
 * Negative numbers will be treated as unsigned positives.
 * @return x to the power n
 * 
 */
public static final double power(double l,int n)
{
    assert n>=0;

    double x=l;
    switch(n){
    case 0: x = 1.0; break;
    case 1: break;
    case 2: x *= x; break;
    case 3: x *= x*x; break;
    case 4: x *= x; x *= x; break;
    case 5: { double y = x*x; x *= y*y; } break;
    case 6: { double y = x*x; x = y*y*y; } break;
    case 7: { double y = x*x; x *= y*y*y; } break;
    case 8: x *= x; x *= x; x *= x; break;
    default:
    {
        int bitMask = n;
        double evenPower = x;
        double result;
        if ( (bitMask & 1) != 0 )
            result = x;
        else
            result = 1;
        bitMask >>>= 1;
        while ( bitMask != 0 ) {
            evenPower *= evenPower;
            if ( (bitMask & 1) != 0 )
                result *= evenPower;
            bitMask >>>= 1;
        } // end while
        x = result;
    }
    }
    return x;
}

For a real exponent you will basically need ways of finding exp and log. You can use Taylor series which are the simplest to get but there are much better method. We have

exp(x) = 1 + x + x^2/2 + x^3/6 + x^4/24 + x^5/120 + x^6/6! + ...

ln(1+x) = x - x^2 /2 + x^3 /3 - x^4 / 4 + x^5 / 5 - x^6/6 + ... |x|<1

To find x^y note ln(x^y) = y*ln(x). Now we need to get the argument in the right range so we can use our power series. Let x = m * 2^ex, the mantissa and exponent chosen so 1/sqrt(2)<= m < sqrt(2) and ln(m*2^ex) = ln(m) + ex*ln(2). Let h = m-1 and find ln(1+h).

Using java and floats as there is an easy way to find the internals of the IEEE representation (I've used float as there are fewer bits to cope with)

int b = Float.floatToIntBits(x);
int sign = (b & 0x80000000) == 0 ? 1 : -1;
int mattissa = b & 0x007fffff;
int ex = ((b & 0x7f800000) >> 23 ) - 127;

in javascript it might be easiest to us Number.toExponential and parse the results.

Next construct a number z in the desired range 1/sqrt(2) < z < sqrt(2)

int bits = mattissa | 0x3f800000;
float z = Float.intBitsToFloat(bits);
if(z>root2) { 
    z = z/2;
    ++ex;
}

Use this function to find the log of 1+x using a taylor series

static float ln1px(float x) {
    float x_2 = x*x; // powers of x
    float x_3 = x_2 * x;
    float x_4 = x_3 * x;
    float x_5 = x_4 * x;
    float x_6 = x_5 * x; 
    float res = x - x_2 /2 + x_3 /3 - x_4 / 4 + x_5 / 5 - x_6/6;
    return res;
}

this seems to be good to three significant figures, often much better when x is close to 0.

The log of our number x can then be found

float w = z - 1;
float ln_z = ln1px(w);
float ln_x = ln_z + ln2 * ex;
System.out.println("ln "+ln_x+"\t"+Math.log(x));

Now to the actual power if we write y = n + a where n is an integer and a is fractional. So x^y=x^(n+a) = x^n * x^a. use the first algorithm in this answer to find the x^n. Writing x=m*2^ex then ln((m*2^ex)^a) = yln(m) + yex*ln(2) and

x^a=exp(ln((m*2^ex)^a)) = exp(a * ln(m)) * exp(a * ln(2))^ex

the two exponential terms have fairly small values so the taylor series should be good.

We need one function for the taylor series of the exponential function

static float exp(float x) {
    float x_2 = x*x; // powers of x
    float x_3 = x_2 * x;
    float x_4 = x_3 * x;
    float x_5 = x_4 * x;
    float x_6 = x_5 * x; 
    float res = 1+ x + x_2 /2 + x_3 /6 + x_4 / 24 + x_5 / 120 + x_6/ 720;
    return res;
}

finally we can put the pieces together

// Get integer and fractional parts of y
int n = (int) Math.floor(y);
float a = y-n;

float x_n = power(x,n);         // x^n
float a_ln_m = a * ln_z;        // ln(m^a) = a ln(m)
float a_ln_2 = a * ln2;         // ln(2^a) = a ln(2)
float m_a = exp(a_ln_m);        // m^a = exp(a ln(m))
float _2_a = exp(a_ln_2);       // 2^a = exp(a ln(2))
float _2_a_ex = power(_2_a,ex); // (2^ex)^a = 2^(a*ex) = (2^a)^ex 
float x_a = m_a * _2_a_ex;      // x^a = m^a * 2^(a*ex)

float x_y = x_n * x_a;          // x^y = x^n * x^a

System.out.println("x^y "+x_y+"\t"+Math.pow(x,y));

That should be the complete program, you need some smarts to cope with negative arguments etc.

Note this is not particularly accurate as I've only used a few terms of the taylor series. Other SO questions have more detailed answers How can I write a power function myself?

Answer from Salix alba on Stack Overflow
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › Math › exp
JavaScript Math exp() - Calculate Exponential
September 27, 2024 - The Math.exp() function in JavaScript is an essential tool for computing the exponential of a number, specifically e^x, where e is Euler's number (approximately 2.71828).
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Exponentiation
Exponentiation (**) - JavaScript | MDN
The exponentiation (**) operator returns the result of raising the first operand to the power of the second operand. It is equivalent to Math.pow(), except it also accepts BigInts as operands.
🌐
TechOnTheNet
techonthenet.com › js › math_exp.php
JavaScript: Math exp() function
This JavaScript tutorial explains how to use the math function called exp() with syntax and examples. In JavaScript, exp() is a function that is used to return e raised to the power of number (which is enumber).
🌐
W3Schools
w3schools.com › jsref › jsref_exp.asp
JavaScript Math exp() Method
Math.exp() is an ECMAScript1 (JavaScript 1997) feature. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
Top answer
1 of 3
4

Heres a nice algorithm for positive integer powers, it starts by dealing with some simple cases and then uses a loop testing the binary bits of the exponent. For example to find 3^11 11 in binary is 1011 so the stages in the loop are

  • bitMask = 1011, evenPower = 3, result = 3
  • bitMask = 101, evenPower = 3*3 = 9, result = 3*9 = 27
  • bitMask = 10, evenPower = 9*9 = 81, result = 27
  • bitMask = 1, evenPower = 81*81 = 6561, result = 27*6561 = 177147

That is the evenPower squares at each loop, and the result gets multiplied by the evenPower if the bottom bit is 1. The code has been lifted from Patricia Shanahan’s method http://mindprod.com/jgloss/power.html which in turn has its roots in Kunth and can be traced back to 200 BC in india.

/**
 * A fast routine for computing integer powers.
 * Code adapted from {@link <a href="http://mindprod.com/jgloss/power.html">efficient power</a>} by Patricia Shanahan [email protected]
 * Almost identical to the method Knuth gives on page 462 of The Art of Computer Programming Volume 2 Seminumerical Algorithms.
 * @param l number to be taken to a power.
 * @param n power to take x to. 0 <= n <= Integer.MAX_VALUE
 * Negative numbers will be treated as unsigned positives.
 * @return x to the power n
 * 
 */
public static final double power(double l,int n)
{
    assert n>=0;

    double x=l;
    switch(n){
    case 0: x = 1.0; break;
    case 1: break;
    case 2: x *= x; break;
    case 3: x *= x*x; break;
    case 4: x *= x; x *= x; break;
    case 5: { double y = x*x; x *= y*y; } break;
    case 6: { double y = x*x; x = y*y*y; } break;
    case 7: { double y = x*x; x *= y*y*y; } break;
    case 8: x *= x; x *= x; x *= x; break;
    default:
    {
        int bitMask = n;
        double evenPower = x;
        double result;
        if ( (bitMask & 1) != 0 )
            result = x;
        else
            result = 1;
        bitMask >>>= 1;
        while ( bitMask != 0 ) {
            evenPower *= evenPower;
            if ( (bitMask & 1) != 0 )
                result *= evenPower;
            bitMask >>>= 1;
        } // end while
        x = result;
    }
    }
    return x;
}

For a real exponent you will basically need ways of finding exp and log. You can use Taylor series which are the simplest to get but there are much better method. We have

exp(x) = 1 + x + x^2/2 + x^3/6 + x^4/24 + x^5/120 + x^6/6! + ...

ln(1+x) = x - x^2 /2 + x^3 /3 - x^4 / 4 + x^5 / 5 - x^6/6 + ... |x|<1

To find x^y note ln(x^y) = y*ln(x). Now we need to get the argument in the right range so we can use our power series. Let x = m * 2^ex, the mantissa and exponent chosen so 1/sqrt(2)<= m < sqrt(2) and ln(m*2^ex) = ln(m) + ex*ln(2). Let h = m-1 and find ln(1+h).

Using java and floats as there is an easy way to find the internals of the IEEE representation (I've used float as there are fewer bits to cope with)

int b = Float.floatToIntBits(x);
int sign = (b & 0x80000000) == 0 ? 1 : -1;
int mattissa = b & 0x007fffff;
int ex = ((b & 0x7f800000) >> 23 ) - 127;

in javascript it might be easiest to us Number.toExponential and parse the results.

Next construct a number z in the desired range 1/sqrt(2) < z < sqrt(2)

int bits = mattissa | 0x3f800000;
float z = Float.intBitsToFloat(bits);
if(z>root2) { 
    z = z/2;
    ++ex;
}

Use this function to find the log of 1+x using a taylor series

static float ln1px(float x) {
    float x_2 = x*x; // powers of x
    float x_3 = x_2 * x;
    float x_4 = x_3 * x;
    float x_5 = x_4 * x;
    float x_6 = x_5 * x; 
    float res = x - x_2 /2 + x_3 /3 - x_4 / 4 + x_5 / 5 - x_6/6;
    return res;
}

this seems to be good to three significant figures, often much better when x is close to 0.

The log of our number x can then be found

float w = z - 1;
float ln_z = ln1px(w);
float ln_x = ln_z + ln2 * ex;
System.out.println("ln "+ln_x+"\t"+Math.log(x));

Now to the actual power if we write y = n + a where n is an integer and a is fractional. So x^y=x^(n+a) = x^n * x^a. use the first algorithm in this answer to find the x^n. Writing x=m*2^ex then ln((m*2^ex)^a) = yln(m) + yex*ln(2) and

x^a=exp(ln((m*2^ex)^a)) = exp(a * ln(m)) * exp(a * ln(2))^ex

the two exponential terms have fairly small values so the taylor series should be good.

We need one function for the taylor series of the exponential function

static float exp(float x) {
    float x_2 = x*x; // powers of x
    float x_3 = x_2 * x;
    float x_4 = x_3 * x;
    float x_5 = x_4 * x;
    float x_6 = x_5 * x; 
    float res = 1+ x + x_2 /2 + x_3 /6 + x_4 / 24 + x_5 / 120 + x_6/ 720;
    return res;
}

finally we can put the pieces together

// Get integer and fractional parts of y
int n = (int) Math.floor(y);
float a = y-n;

float x_n = power(x,n);         // x^n
float a_ln_m = a * ln_z;        // ln(m^a) = a ln(m)
float a_ln_2 = a * ln2;         // ln(2^a) = a ln(2)
float m_a = exp(a_ln_m);        // m^a = exp(a ln(m))
float _2_a = exp(a_ln_2);       // 2^a = exp(a ln(2))
float _2_a_ex = power(_2_a,ex); // (2^ex)^a = 2^(a*ex) = (2^a)^ex 
float x_a = m_a * _2_a_ex;      // x^a = m^a * 2^(a*ex)

float x_y = x_n * x_a;          // x^y = x^n * x^a

System.out.println("x^y "+x_y+"\t"+Math.pow(x,y));

That should be the complete program, you need some smarts to cope with negative arguments etc.

Note this is not particularly accurate as I've only used a few terms of the taylor series. Other SO questions have more detailed answers How can I write a power function myself?

2 of 3
2

Those are some really nice examples, here is a simpler one too.

function exponential(a,b){
    var c = 1;
    for(var i=1; i<=b; i++){
        c = c * a;
    }
    return c;
}

now call the function:

exponential(2,4);

Edit: It only works on integer, but it's simple and quick.

🌐
Programiz
programiz.com › javascript › library › math › exp
JavaScript Math.exp()
The Math.exp() method returns e (Euler's constant) raised to the given power. It is equivalent to ex in mathematics. In this tutorial, you will learn about the JavaScript Math.exp() method with the help of examples.
🌐
W3Schools
w3schools.com › howto › howto_js_exponentiation.asp
How To Use JavaScript Exponentiation
The exponentiation assignment operator (**=) raises the value of a variable to the power of the right operand. let x = 5; x **= 2; // result 25 Try it Yourself » · Read more about JavaScript Operators in our JavaScript Operator Tutorial.
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Number › toExponential
Number.prototype.toExponential() - JavaScript | MDN
The toExponential() method of Number values returns a string representing this number in exponential notation. function expo(x, f) { return Number.parseFloat(x).toExponential(f); } console.log(expo(123456, 2)); // Expected output: "1.23e+5" console.log(expo("123456")); // Expected output: ...
🌐
DEV Community
dev.to › mayallo › exponentiation-in-javascript-a-beginners-guide-5gdj
Exponentiation in JavaScript: A Beginner’s Guide - DEV Community
July 8, 2023 - If, for instance, we raise 2 to the power of 3, we calculate it as 2 * 2 * 2, which gives us the result of 8. In JavaScript, you can use either the ** operator introduced in ES6 or the method Math.pow() when evaluating exponents.
🌐
Math.js
mathjs.org › docs › reference › functions › exp.html
math.js | an extensive math library for JavaScript and Node.js
Calculate the exponential of a value. For matrices, if you want the matrix exponential of square matrix, use the expm function; if you want to take the exponential of each element, see the examples.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-math-exp-method
JavaScript Math exp() Method | GeeksforGeeks
July 15, 2024 - The Math.SQRT2 is a property in JavaScript which is simply used to find the value of the square root of 2, whose value is approximately 1.4142. That is, √ 2 = 1.4142 Syntax: Math.SQRT2; Return Value: It simply returns the value of the square ...
🌐
W3Schools
w3schools.com › jsref › jsref_toexponential.asp
JavaScript toExponential() Method
The toExponential() method converts a number into an exponential notation. let num = 5.56789; let n = num.toExponential(3); Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send ...
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › Math › expm1
JavaScript Math expm1() - Exponential Minus One | Vultr Docs
September 27, 2024 - ... let decay = Math.expm1(-0.03 ... Explain Code · expm1() can be used to calculate the remained amount after a decay process, considering continuous decay rates over periods. The expm1() function in JavaScript provides ...
🌐
W3Schools
w3schools.com › jsref › jsref_pow.asp
JavaScript Math pow() Method
Math.pow() is an ECMAScript1 (JavaScript 1997) feature. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
🌐
TutorialsPoint
tutorialspoint.com › home › javascript › javascript math expressions
JavaScript Math Expressions
September 1, 2008 - The Math.exp() method in JavaScript is used to return the result of raising Euler's number (approximately equal to 2.718) to the power of a specified number. It calculates the exponential value of the provided number, where Euler's number raised ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › exponentiation-arithmetic-operator-in-javascript
Exponentiation(**) Arithmetic Operator in JavaScript - GeeksforGeeks
July 23, 2025 - JavaScript exponentiation(**) operator in JavaScript is represented by "**" and is used to find the power of the first operator raised to the second operator. This operator is equal to Math.pow() but makes the code simpler and can even accept ...
Top answer
1 of 3
1

Numbers are numbers, the values 5.02041E+12 and 5020410000000 do not differ internally:

// values in code:
var withe=5.02041E+12;
var withoute=5020410000000;
console.log(withe,"?=",withoute,withe===withoute);

// values parsed from strings:
var stringwithe="5.02041E+12";
var stringwithoute="5020410000000";
var a=parseFloat(stringwithe);
var b=parseFloat(stringwithoute);
console.log(a,"?=",b,a===b);

And you can also see that when you simply display a number, it will not use the scientific notation by default, actually you would have to ask for it via using toExponential()


One thing you can worry about is the internal precision of Number. It has a method isSafeInteger() and various fields, like MAX_SAFE_INTEGER. Surpassing that value can lead to unexpected results:

var a=Number.MAX_SAFE_INTEGER;
console.log("This is safe:",a,Number.isSafeInteger(a));
a++;
for(var i=0;i<5;i++)
  console.log("These are not:",a++,Number.isSafeInteger(a));

So the loop can not increment a any further, because there is no such number as 9007199254740993 here. The next number which exists after 9007199254740992 is 9007199254740994. But these numbers are more than 1000x greater than the 5020410000000 in the question.

2 of 3
0

You can just use toPrecision on every number and ensure it converts

const valueOne = 5.02041E+12;
const valueTwo = 1234;

const precisionValueOne = valueOne.toPrecision(); // "5020410000000"
const precisionValue2 = valueTwo.toPrecision(); // "1234"

You can then, optionally convert it back to numbers:

sanitizedValueOne = Number(precisionValueOne); // 5020410000000
sanitizedValueTwo = Number(precisionValueTwo); // 1234