Double和Float中的NaN和Infinity
生活随笔
收集整理的這篇文章主要介紹了
Double和Float中的NaN和Infinity
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
對于Double和Float這種浮點型來說,存在無窮大(POSTIVE_INFINITY)和無窮小(NAGATIVE_INFINITY),NaN的概念。
注意:NaN在任何時候都不會相等。
public class Test {
public static void main(String[] args) {
System.out.println(Double.NEGATIVE_INFINITY==Float.NEGATIVE_INFINITY); // TRUE
System.out.println(Double.NEGATIVE_INFINITY==Double.NEGATIVE_INFINITY); // TRUE
System.out.println(Float.NEGATIVE_INFINITY==Float.NEGATIVE_INFINITY); // TRUE
System.out.println(Float.NaN==Float.NaN); // FALSE
System.out.println(Double.NaN==Double.NaN); // FALSE
}
}
那么什么時候會出現這種情況呢?下圖說明:
如何去判斷一個數是不是infinity或者NaN呢?
1.isInifinite() 用于判斷一個數是不是infinity(無窮大,包括正無窮和負無窮);
1 /**
2 * Returns {@code true} if the specified number is infinitely
3 * large in magnitude, {@code false} otherwise.
4 *
5 * @param v the value to be tested.
6 * @return {@code true} if the value of the argument is positive
7 * infinity or negative infinity; {@code false} otherwise.
8 */
9 public static boolean isInfinite(double v) {
10 return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY);
11 }
2.isNaN() 用于判斷一個數是否是一個數;
1 /**
2 * Returns {@code true} if the specified number is a
3 * Not-a-Number (NaN) value, {@code false} otherwise.
4 *
5 * @param v the value to be tested.
6 * @return {@code true} if the value of the argument is NaN;
7 * {@code false} otherwise.
8 */
9 public static boolean isNaN(double v) {
10 return (v != v);
11 }
總結
以上是生活随笔為你收集整理的Double和Float中的NaN和Infinity的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux中设置vim自动在运算符号两边
- 下一篇: php调用API支付接口(转自刘68)