Java/Data Type/double

Материал из Java эксперт
Перейти к: навигация, поиск

A Program That Uses the Mathematical Methods of the Math Class

   <source lang="java">
   

public class MainCLass {

 public static void main(String[] args) {
   int a = 10;
   int b = -50;
   int c = 3;
   double x = 25.0;
   double y = 3.0;
   double z = 4.0;
   System.out.println("abs(b)     = " + Math.abs(b));
   System.out.println("cbrt(x)   = " + Math.cbrt(x));
   System.out.println("exp(y)     = " + Math.exp(z));
   System.out.println("hypot(y, z)= " + Math.hypot(y, z));
   System.out.println("log(y)    = " + Math.log(y));
   System.out.println("log10(y)  = " + Math.log10(y));
   System.out.println("max(a, b) = " + Math.max(a, b));
   System.out.println("min(a, b) = " + Math.min(a, b));
   System.out.println("pow(a, c) = " + Math.pow(a, c));
   System.out.println("random()  = " + Math.random());
   System.out.println("signum(b) = " + Math.signum(b));
   System.out.println("sqrt(x)   = " + Math.sqrt(y));
 }

}


 </source>
   
  
 
  



A Program That Uses the Rounding Methods of the Math Class

   <source lang="java">
   

public class MainCLass {

 public static void main(String[] args) {
   double x = 2.4;
   double y = 9.5;
   double z = -1.3;
   System.out.println("round(x) = " + Math.round(x));
   System.out.println("round(y) = " + Math.round(y));
   System.out.println("round(z) = " + Math.round(z));
   System.out.println();
   System.out.println("ceil(x) = " + Math.ceil(x));
   System.out.println("ceil(y) = " + Math.ceil(y));
   System.out.println("ceil(z) = " + Math.ceil(z));
   System.out.println();
   System.out.println("floor(x) = " + Math.floor(x));
   System.out.println("floor(y) = " + Math.floor(y));
   System.out.println("floor(z) = " + Math.floor(z));
   System.out.println();
   System.out.println("rint(x) = " + Math.rint(x));
   System.out.println("rint(y) = " + Math.rint(y));
   System.out.println("rint(z) = " + Math.rint(z));
 }

}


 </source>
   
  
 
  



Binary search

   <source lang="java">
   
      

class MainClass {

 public static void main(String[] args) {
   double[] x = { -39, -3, 6, 10, 4, 9, 10 };
   double value = 8;
   int lower = 0, upper = x.length - 1;
   while (lower <= upper) {
     int middle = (lower + upper) / 2;
     if (value > x[middle])
       lower = middle + 1;
     else if (value < x[middle])
       upper = middle - 1;
     else
       break;
   }
   if (lower > upper)
     System.out.println("Not found");
   else
     System.out.println("Found");
 }

}


 </source>
   
  
 
  



Compare Two Java double Arrays

   <source lang="java">
  

import java.util.Arrays; public class Main {

 public static void main(String[] args) {
   double[] a1 = new double[] { 1.3, 7.2, 4.2 };
   double[] a2 = new double[] { 1.3, 7.2, 4.2 };
   System.out.println(Arrays.equals(a1, a2));
 }

}


 </source>
   
  
 
  



Compute the value of 2/3 of 5

   <source lang="java">
  

/** Compute the value of 2/3 of 5 */ public class FractMult {

 public static void main(String[] u) {
   double d1 = 0.666 * 5;  // fast but obscure and inaccurate: convert
   System.out.println(d1); // 2/3 to 0.666 in programmer"s head
   double d2 = 2/3 * 5;  // wrong answer - 2/3 == 0, 0*5 = 0
   System.out.println(d2);
   double d3 = 2d/3d * 5;  // "normal"
   System.out.println(d3);
   double d4 = (2*5)/3d;  // one step done as integers, almost same answer
   System.out.println(d4);
   int i5 = 2*5/3;      // fast, approximate integer answer
   System.out.println(i5);
 }

}



 </source>
   
  
 
  



Convert from double to String

   <source lang="java">
  

public class Main {

 public static void main(String[] args) throws Exception {
   String str = Double.toString(23);
 }

}


 </source>
   
  
 
  



Convert from String to double

   <source lang="java">
  

public class Main {

 public static void main(String[] args) throws Exception {
   Double d = Double.valueOf("0.9D").doubleValue();
 }

}


 </source>
   
  
 
  



Converting a String to a double type Number

   <source lang="java">
  

public class Main {

 public static void main(String[] argv) throws Exception {
   double d = Double.parseDouble("123.4e10");
   System.out.println(d);
 }

}


 </source>
   
  
 
  



Convert java Double to numeric primitive data types

   <source lang="java">
  

public class Main {

 public static void main(String[] args) {
   Double dObj = new Double("10.50");
   byte b = dObj.byteValue();
   System.out.println(b);
   short s = dObj.shortValue();
   System.out.println(s);
   int i = dObj.intValue();
   System.out.println(i);
   float f = dObj.floatValue();
   System.out.println(f);
   double d = dObj.doubleValue();
   System.out.println(d);
 }

} /* 10 10 10 10.5 10.5

  • /


 </source>
   
  
 
  



Convert Java String to Double

   <source lang="java">
  
     

public class Main {

 public static void main(String[] args) {
   Double dObj1 = new Double("100.564");
   System.out.println(dObj1);
   Double dObj2 = Double.valueOf("10.6");
   System.out.println(dObj2);
   double d = Double.parseDouble("76.39");
   System.out.println(d);
 }

}


 </source>
   
  
 
  



Create a Double object using one of the below given constructors

   <source lang="java">
  

public class Main {

 public static void main(String[] args) {
   double d = 10.10;
   Double dObj1 = new Double(d);
   System.out.println(dObj1);
   Double dObj3 = new Double("25.34");
   System.out.println(dObj3);
 }

}


 </source>
   
  
 
  



Double Array

   <source lang="java">
  

public class Main {

 public static void main(String[] args) {
   int[][] sums = new int[10][12];
   for (int row = 0; row < 10; row++) {
     for (int col = 0; col < 12; col++) {
       sums[row][col] = row + col;
     }
   }
   for (int row = 0; row < sums.length; row++) {
     for (int col = 0; col < sums[row].length; col++) {
       System.out.print(sums[row][col] + "\t");
     }
     System.out.println();
   }
 }

}


 </source>
   
  
 
  



Double class creates primitives that wrap themselves around data items of the double data type

   <source lang="java">
   
       

public class MainClass {

 public static void main(String[] args) {
   double d = 3.5;
   Double d2 = new Double(d);
   System.out.println(d2.doubleValue());
 }

}


 </source>
   
  
 
  



Get Double Number

   <source lang="java">
  

import java.awt.*; import java.awt.event.*; public class GetNumber {

 private static Number NAN = new Double(Double.NaN);
 /* Process one String, returning it as a Number subclass
  * Does not require the GUI.
  */
 public static Number process(String s) {
   if (s.matches(".*[.dDeEfF]")) {
     try {
       double dValue = Double.parseDouble(s);
       System.out.println("It"s a double: " + dValue);
       return new Double(dValue);
     } catch (NumberFormatException e) {
       System.out.println("Invalid a double: " + s);
       return NAN;
     }
   } else // did not contain . d e or f, so try as int.
     try {
       int iValue = Integer.parseInt(s);
       System.out.println("It"s an int: " + iValue);
       return new Integer(iValue);
     } catch (NumberFormatException e2) {
       System.out.println("Not a number:" + s);
       return NAN;
     }
 }
 public static void main(String[] ap) {
   process("0");
   process("1111111111");
 }

}



 </source>
   
  
 
  



Gets the maximum of three double values.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

*

Provides extra functionality for Java Number classes.

*
* @author 
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/

public class Main {

 /**
*

Gets the maximum of three double values.

  * 
*

If any value is NaN, NaN is * returned. Infinity is handled.

  *
  * @param a  value 1
  * @param b  value 2
  * @param c  value 3
  * @return  the largest of the values
  * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently
  */
 public static double max(double a, double b, double c) {
     return Math.max(Math.max(a, b), c);
 }

}


 </source>
   
  
 
  



Gets the minimum of three double values.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

*

Provides extra functionality for Java Number classes.

*
* @author 
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/

public class Main {

 /**
*

Gets the minimum of three double values.

  * 
*

If any value is NaN, NaN is * returned. Infinity is handled.

  * 
  * @param a  value 1
  * @param b  value 2
  * @param c  value 3
  * @return  the smallest of the values
  * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently
  */
 public static double min(double a, double b, double c) {
     return Math.min(Math.min(a, b), c);
 }

}


 </source>
   
  
 
  



Get the next machine representable number after a number, moving in the direction of another number.

   <source lang="java">
 

import java.io.File; /*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * Get the next machine representable number after a number, moving
  * in the direction of another number.
*

* If direction is greater than or equal tod, * the smallest machine representable number strictly greater than * d is returned; otherwise the largest representable number * strictly less than d is returned.

*

* If d is NaN or Infinite, it is returned unchanged.

  * 
  * @param d base number
  * @param direction (the only important thing is whether
  * direction is greater or smaller than d)
  * @return the next machine representable number in the specified direction
  * @since 1.2
  */
 public static double nextAfter(double d, double direction) {
     // handling of some important special cases
     if (Double.isNaN(d) || Double.isInfinite(d)) {
             return d;
     } else if (d == 0) {
             return (direction < 0) ? -Double.MIN_VALUE : Double.MIN_VALUE;
     }
     // special cases MAX_VALUE to infinity and  MIN_VALUE to 0
     // are handled just as normal numbers
     // split the double in raw components
     long bits     = Double.doubleToLongBits(d);
     long sign     = bits & 0x8000000000000000L;
     long exponent = bits & 0x7ff0000000000000L;
     long mantissa = bits & 0x000fffffffffffffL;
     if (d * (direction - d) >= 0) {
             // we should increase the mantissa
             if (mantissa == 0x000fffffffffffffL) {
                     return Double.longBitsToDouble(sign |
                                     (exponent + 0x0010000000000000L));
             } else {
                     return Double.longBitsToDouble(sign |
                                     exponent | (mantissa + 1));
             }
     } else {
             // we should decrease the mantissa
             if (mantissa == 0L) {
                     return Double.longBitsToDouble(sign |
                                     (exponent - 0x0010000000000000L) |
                                     0x000fffffffffffffL);
             } else {
                     return Double.longBitsToDouble(sign |
                                     exponent | (mantissa - 1));
             }
     }
 }

}


 </source>
   
  
 
  



Java Double compare example

   <source lang="java">
  

public class Main {

 public static void main(String[] args) {
   double d1 = 5.5;
   double d2 = 5.4;
   int i1 = Double.rupare(d1, d2);
   if (i1 > 0) {
     System.out.println(">");
   } else if (i1 < 0) {
     System.out.println("<");
   } else {
     System.out.println("=");
   }
   Double dObj1 = new Double("5.5");
   Double dObj2 = new Double("5.4");
   int i2 = dObj1.rupareTo(dObj2);
   if (i2 > 0) {
     System.out.println(">");
   } else if (i2 < 0) {
     System.out.println("<");
   } else {
     System.out.println("=");
   }
 }

}


 </source>
   
  
 
  



Java double: double is 64 bit double precision type and used when fractional precision calculation is required.

   <source lang="java">
  

public class Main {

 public static void main(String[] args) {
   double d = 1234.56;
   System.out.println("Value of double variable d is :" + d);
 }

} //Value of double variable d is :1234.56


 </source>
   
  
 
  



Java Double isInfinite

   <source lang="java">
  

public class Main {

 public static void main(String[] args) {
   double d = (double) 4 / 0;
   boolean b1 = Double.isInfinite(d);
   System.out.println(b1);
   Double dObj = new Double(d);
   boolean b2 = dObj.isInfinite();
   System.out.println(b2);
 }

}


 </source>
   
  
 
  



Java Double isNaN method

   <source lang="java">
  

public class Main {

 public static void main(String[] args) {
   double d = Math.sqrt(-10);
   boolean b1 = Double.isNaN(d);
   System.out.println(b1);
   Double dObj = new Double(d);
   boolean b2 = dObj.isNaN();
   System.out.println(b2);
 }

}


 </source>
   
  
 
  



Linear Searching double Arrays

   <source lang="java">
   
      

class MainClass {

 public static void main(String[] args) {
   double[] x = { 92.3, 45.2, 6.8, -3.6, 10, 9000, -39 };
   int i;
   for (i = 0; i < x.length; i++)
     if (x[i] == 9000)
       break;
   if (i == x.length)
     System.out.println("Not found");
   else
     System.out.println("Found");
 }

}


 </source>
   
  
 
  



Min and Max values of data type double

   <source lang="java">
  

public class Main {

   public static void main(String[] args) {
       System.out.println(Double.MIN_VALUE);
       System.out.println(Double.MAX_VALUE);
   }

} /* 4.9E-324 1.7976931348623157E308

  • /


 </source>
   
  
 
  



Obtaining the integer and fractional parts

   <source lang="java">
  

class IntFrac {

 public static void main(String[] args) {
   double num;
   long iPart;
   double fPart;
   // Get user input
   num = 2.3d;
   iPart = (long) num;
   fPart = num - iPart;
   System.out.println("Integer part = " + iPart);
   System.out.println("Fractional part = " + fPart);
 }

}



 </source>
   
  
 
  



Returns the sign for double precision x

   <source lang="java">
 

import java.math.BigDecimal; /*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * Returns the 
  * for double precision x.
*

* For a double value x, this method returns * +1.0 if x > 0, 0.0 if * x = 0.0, and -1.0 if x < 0. * Returns NaN if x is NaN.

  * 
  * @param x the value, a double
  * @return +1.0, 0.0, or -1.0, depending on the sign of x
  */
 public static double sign(final double x) {
     if (Double.isNaN(x)) {
         return Double.NaN;
     }
     return (x == 0.0) ? 0.0 : (x > 0.0) ? 1.0 : -1.0;
 }

}


 </source>
   
  
 
  



Show INFINITY and NaN

   <source lang="java">
  

/**

* Show INFINITY and NaN
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: InfNaN.java,v 1.4 2004/02/09 03:33:57 ian Exp $
*/

public class InfNaN {

 //+
 public static void main(String[] argv) {
   double d = 123;
   double e = 0;
   if (d/e == Double.POSITIVE_INFINITY)
     System.out.println("Check for POSITIVE_INFINITY works");
   double s = Math.sqrt(-1);
   if (s == Double.NaN)
     System.out.println("Comparison with NaN incorrectly returns true");
   if (Double.isNaN(s))
     System.out.println("Double.isNaN() correctly returns true");
 }
 //-

}



 </source>
   
  
 
  



Ternary operator on double value

   <source lang="java">
  

public class Main {

 public static void main(String[] args) {
   
   double d = 5.0;
   d *= 4.0;
   System.out.println("d = " + d);
   System.out.println("Ternary: " + (d == 5 ? "yes" : "no"));
 }

}


 </source>
   
  
 
  



The Circle Area Calculator

   <source lang="java">
   

import java.util.Scanner; public class CircleAreaApp {

 static Scanner sc = new Scanner(System.in);
 public static void main(String[] args) {
   System.out.print("Enter the radius of your circle: ");
   double r = sc.nextDouble();
   double area = Math.PI * (r * r);
   System.out.println("The area is " + area);
 }

}


 </source>
   
  
 
  



Use Double constructor to convert double primitive type to a Double object.

   <source lang="java">
  

public class Main {

 public static void main(String[] args) {
   double d = 10.56;
   Double dObj = new Double(d);
   System.out.println(dObj);
 }

}


 </source>
   
  
 
  



Use toString method of Double class to convert Double into String.

   <source lang="java">
  

public class Main {

 public static void main(String[] args) {
   Double dObj = new Double(10.25);
   String str = dObj.toString();
   System.out.println(str);
 }

}


 </source>