Which is the fastest way to get the absolute value of a number

后端 未结 14 895
陌清茗
陌清茗 2020-12-07 19:10

Which is the fastest way to implement an operation that returns the absolute value of a number?

x=root(x²)

or

if !isPositiv         


        
14条回答
  •  没有蜡笔的小新
    2020-12-07 19:25

    For a list of negative numbers:

    if you have zero stored in memory, simply use 0 - x, where x is the negative number.

    Or if you do not have zero stored in memory:

    x-x-x, where x is the negative number.

    Or, with brackets for clarity:

    (x) - (x) - (x) => (-n) - (-n) - (-n), where x = -n

    i.e. subtract the negative number from itself to get zero, then subtract it from zero.

提交回复
热议问题