Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When dealing with double data types is multiplying by the inverse better or worse?

Which way is faster? Which way uses less memory? Which way is preferred?

How does MSIL handle this?

SquareInches = MMSquared / 645.16 
SquareInches = MMSquared * 0.0015500031000062000124000248000496

NB: 10K users will note that this is a duplicate of this question, which was deleted because the original question asker decided to berate everyone in the 'comments' section of the question.

This question was reposted because it is a 'good' question.

Please 'uncheck' Community Wiki for your answer, as I'm only posting this as CW so that it's not seen as a 'reputation' grab.

Related Question:

Should I use multiplication or division?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
758 views
Welcome To Ask or Share your Answers For Others

1 Answer

Multiplying by the inverse is faster. Compilers don't optimize this automatically because it can result in a small loss of precision. (This actually came up on a D newsgroup Walter Bright frequents, and he made it clear that compilers do not do this automatically.) You should normally divide because it is more readable and accurate.

If you are executing a piece of floating point code a billion times in a loop and you don't care about a small loss of precision and you will be dividing by the same number several times, then multiplying by the inverse can be a good optimization. I have actually gotten significant real world speedup in a few cases like the ones described by multiplying by the inverse, but these are extreme edge cases in loops executed several billion times that pretty much do nothing but multiply floats.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...