简体   繁体   中英

Is there any reason to use Math.pow() with literals rather than the result itself?

I'm currently looking at existing code. There are many methods that have been written to model existing formulas. I stumbled over dozens of instances of code like Math.pow(10.0D, 3.0D) , Math.pow(300.0D, 2.0D) and also stuff like 1.5D * 1000.0D .

Now, before I go ahead and replace all these with their respective results ( 1000d , 90000d , 1500d for the examples above), I wanted to figure out if there are any good reasons to keep with the original notation?

The only thing that came to my mind is to preserve the resemblance of the code to the modeled formulas. Are there any other reasons I fail to see?

It's essentially all about readability. You'll see this sort of code style more commonly when dealing with time, for example:

Thread.sleep(5 * 60 * 1000);

This style makes it more obvious that the thread will sleep for 5 minutes. When dealing with mathematical formulas, it's common to keep each value of the formula intact so it's obvious what formula is being used and that it is being used correctly.

Programmers like to write things out long hand for the sake of readability: knowing, for example, that there are 86400 seconds in a normal day really belongs to attendees of pub quizzes, not programmers.

But that said, I'd be inclined to not use Math.pow for this.

The chief reason being that it's probably not a compile time evaluable constant expression , although that could depend on the compiler.

You might find that pow(x, y) is implemented as exp(y log x) : this can "go off" for surprisingly trivial-looking values of x and y due to a floating point double being only accurate to around 15 decimal significant figures.

(Currently the JLS specifies only one Math.pow function which takes two double arguments. If you were to use integral literals, then the compiler would automatically convert them to double types prior to calling the function. It appears that the author is using double literals to guard against the possibility of future overloads of Math.pow being introduced.)

In your particular cases, I'd consider replacing Math.pow(300.0D, 2.0D) with 300.0 * 300.0 and Math.pow(10.0D, 3.0D) with 10.0 * 10.0 * 10.0 . But do check that these values are identical to the original ones; and investigate the impact of any discrepancies carefully.

It could make it easier to verify that a formula was translated correctly into code. Consider also whether some of these numeric literals should be replaced with named constants to further improve readability. Without knowing the context, it looks a lot of "magic numbers".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM