Tuesday 15 May 2018

Check if a double is infinite in Java

"java.lang.Double" class provides "isInfinite()" method to check whether given double value is infinitely large in magnitude.


"isInifinte()" method is available in two forms.

public boolean isInfinite()
public static boolean isInfinite(double v)
Both the methods return true if the specified number is infinitely large in magnitude, false otherwise.

Test.java
package com.sample.test;

public class Test {

 private static double factorial(int num) {
  double result = 1;

  for (int i = 2; i <= num; i++) {
   result = result * i;
   if (Double.isInfinite(result)) {
    throw new ArithmeticException("Overflow");
   }
  }
  
  return result;
 }

 public static void main(String... args) {
  System.out.println(factorial(1000));
 }
}

When you ran above application, you will end up in ArithmeticException.

Exception in thread "main" java.lang.ArithmeticException: Overflow
         at com.sample.app.Test.factorial(Test.java:11)
         at com.sample.app.Test.main(Test.java:19)

You may like
Comment multiple lines inEclipse


No comments:

Post a Comment