Java - Math nextAfter(double x, double y) 方法



描述

Java Math nextAfter(double start, double direction) 方法返回第一個引數在第二個引數方向上的相鄰浮點數。如果兩個引數比較相等,則返回第二個引數。特殊情況 -

  • 如果任一引數為 NaN,則返回 NaN。

  • 如果兩個引數都是帶符號的零,則 direction 返回不變(如返回引數相等時返回第二個引數的要求所暗示的那樣)。

  • 如果start 為 Double.MIN_VALUE 且 direction 的值為結果應具有較小幅度的值,則返回與 start 符號相同的零。

  • 如果start 為無窮大且 direction 的值為結果應具有較小幅度的值,則返回與 start 符號相同的 Double.MAX_VALUE。

  • 如果start 等於 Double.MAX_VALUE 且 direction 的值為結果應具有較大幅度的值,則返回與 start 符號相同的無窮大。

宣告

以下是 java.lang.Math.nextAfter() 方法的宣告

public static double nextAfter(double start, double direction)

引數

  • start − 起始浮點值

  • direction − 指示應返回 start 的哪個鄰居或 start 的值

返回值

此方法返回 start 在 direction 方向上的相鄰浮點數。

異常

示例:獲取兩個正值的 Next After 值

以下示例演示了 Math nextAfter() 方法對兩個正值的用法。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get two double numbers
      double x = 98759.765;
      double y = 154.28764;
   
      // print the next number for x towards y
      System.out.println("Math.nextAfter(" + x + "," + y + ")="
         + Math.nextAfter(x, y));

      // print the next number for y towards x
      System.out.println("Math.nextAfter(" + y + "," + x + ")="
         + Math.nextAfter(y, x));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果 -

Math.nextAfter(98759.765,154.28764)=98759.76499999998
Math.nextAfter(154.28764,98759.765)=154.28764000000004

示例:獲取正值和負值的 Next After 值

以下示例演示了 Math nextAfter() 方法對正值和負值的用法。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get two double numbers
      double x = -98759.765;
      double y = 154.28764;
   
      // print the next number for x towards y
      System.out.println("Math.nextAfter(" + x + "," + y + ")="
         + Math.nextAfter(x, y));

      // print the next number for y towards x
      System.out.println("Math.nextAfter(" + y + "," + x + ")="
         + Math.nextAfter(y, x));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果 -

Math.nextAfter(-98759.765,154.28764)=-98759.76499999998
Math.nextAfter(154.28764,-98759.765)=154.28763999999998

示例:獲取兩個負值的 Next After 值

以下示例演示了 Math nextAfter() 方法對負值的用法。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get two double numbers
      double x = -98759.765;
      double y = -154.28764;
   
      // print the next number for x towards y
      System.out.println("Math.nextAfter(" + x + "," + y + ")="
         + Math.nextAfter(x, y));

      // print the next number for y towards x
      System.out.println("Math.nextAfter(" + y + "," + x + ")="
         + Math.nextAfter(y, x));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果 -

Math.nextAfter(-98759.765,-154.28764)=-98759.76499999998
Math.nextAfter(-154.28764,-98759.765)=-154.28764000000004
java_lang_math.htm
廣告