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

后端 未结 14 887
陌清茗
陌清茗 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:31

    The modulo operation is used to find a remainder, you mean absolute value. I modified the question because it should be if !pos(x) then x = x*-1. (not was missing)

    I wouldn't worry about the efficiency of an if statement. Instead focus on the readability of your code. If you identify that there is an efficiency problem, then focus on profiling your code to find real bottlenecks.

    If you want to keep an eye out for efficiency while you code, you should only worry about the big-O complexity of your algorithms.

    If statements are very efficient, it evaluates whatever expression and then simply changes the program counter based on that condition. The program counter stores the address of the next instruction to be executed.

    Mulitplication by -1 and checking if a value is greater than 0 both can be reduced to a single assembly instruction.

    Finding the root of a number and squaring that number first is definitely more operations than the if with a negation.

提交回复
热议问题