且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

被乘以逆更好或更坏?

更新时间:2023-10-03 21:47:52

由逆乘快。编译器不优化该自动,因为它会导致小损失precision。 (这实际上提出了在一个D新闻组沃尔特明亮流连,他明确表示,编译器不会自动执行此操作。)你通常要分,因为它更具有可读性和准确性。

如果您正在执行一条浮点$ C $钙在循环十亿倍你不计较小的损失precision 你会用相同的号码多次分裂,然后由逆相乘可以是一个很好的优化。其实我已经得到显著现实世界加速在少数情况下,像由倒数乘以所描述的那些,但这些都是在循环中最边缘的情况下执行数十亿倍,pretty的多少做什么,但乘花车。

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?

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.