In this case, the performance gain of multiplying by -1 is probably minimal. When you use Math. But, yes, negating a negative sign is the sole purpose. So unless you're absolutely sure that the number is negative to begin with, you have to do some tests, which cost more time.
Might as well do math. Apart from that I agree that you should use abs if you don't know the sign of the number beforehand. I would not care for speed but for readability. Stack Overflow for Teams — Collaborate and share knowledge with a private group.
Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Which is faster: Math. Ask Question. Asked 12 years, 10 months ago. Active 5 years, 8 months ago. Viewed 33k times. Abs method in the base class library in the. NET Framework provides some error-checking that may be useful. Tip: The C compiler does overload resolution based on the parameter type. It infers the appropriate method to use. Next: This example shows the absolute value of a negative integer, a positive integer, a negative double and a positive double.
The C compiler resolves the four calls to Math. Abs to the System. Math class. It uses the version with an int in its signature for the first two calls, and the version with double for the second two. Tip: You could cast the variables before passing them as parameters to force the compiler to use a different overload.
The example program prints eight numbers. Each numeric literal in the source is printed in its initial form and the result of the Math. Abs computation. Compute the squared absolute value of a single-precision floating-point number.
Compute a sum of squared absolute values incrementally. Compute an absolute value of a complex number. Compute an arithmetic mean of squared absolute values incrementally.
Artificial Intelligence. Cloud Computing. Data Science. Angular 7. Machine Learning. Data Structures. Operating System. Computer Network. Compiler Design.
0コメント