Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Math.pow more expensive than multiplication using temporary assignments?

When porting a javascript library to Python, I found this code:

return Math.atan2(
    Math.sqrt(
       (_ = cosφ1 * sinΔλ) * _ + (_ = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * _
    ), 
    sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ
);

Am I wrong or (_ = cosφ1 * sinΔλ) * _ could be written like Math.pow(cosφ1 * sinΔλ, 2)?

I guess the author is trying to avoid using Math.pow, is this expensive in javascript compared to the temporary assignment?

[update]

As of late 2016, with Chrome 53.0 (64-bit) looks like the difference is not as large as it used to be.

like image 329
Paulo Scardine Avatar asked Aug 22 '13 14:08

Paulo Scardine


People also ask

Is pow faster than multiplication?

When not compiling with -ffast-math, direct multiplication was significantly faster than std::pow , around two orders of magnitude faster when comparing x * x * x and code:std::pow(x, 3) . One comment that I've got was to test for which n is code:std::pow(x, n) becoming faster than multiplying in a loop.

Does math POW return a double?

pow() is used to return the value of first argument raised to the power of the second argument. The return type of pow() method is double.

How does math POW work java?

pow(double a, double b) returns the value of a raised to the power of b . It's a static method on Math class, which means you don't have to instantiate a Math instance to call it. The power of a number is the number of times the number is multiplied by itself.

How do you multiply to the power in Java?

pow() is an built-in method in Java Math class and is used to calculate the power of a given number. The power of a number refers to how many times to multiply the number with itself.

How do you write a power of 10 in Java?

double number = 7893.147895673; int dp = 7; String pattern = "."; for (int i = 1; i <= dp; i++) { pattern += "#"; }//for (int i = 1; i <= dp; i++) DecimalFormat df = new DecimalFormat (pattern); System.


1 Answers

The only reason I can think of is performance. First let's test if they actually do the same and we didn't overlook something.

var test = (test = 5 * 2) * test; // 100
Math.pow(5 * 2, 2); // 100

As expected, that's proven to do the same. Now let's see if they have different performances using jsperf. Check it out here: http://jsperf.com/...num-self

The differences for Firefox 23 are very small, but for Safari the difference was much bigger. Using Math.pow seems to be more expensive there.

like image 112
Broxzier Avatar answered Sep 29 '22 08:09

Broxzier