Fastest way to get sign in Java?

前端 未结 3 875
忘了有多久
忘了有多久 2021-01-01 10:39

I\'d like to get the sign of a float value as an int value of -1 or 1.

Avoiding conditionals is always a good idea in reducing computationa

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 11:15

    You should only try to use hard to read/understand optimizations, if it is absolutely neccessary.

    The issue with

    int sign = Math.signum(a);
    

    may be that it returns 0 if 0.0==a

    But you should rely on existing library functions whenever possible to keep your code easy to read/understand.

    If you want 1 for 0.0==a what about this:

    int sign = (0>a)?-1:1;
    

提交回复
热议问题