Java/Data Type/double
Содержание
- 1 A Program That Uses the Mathematical Methods of the Math Class
- 2 A Program That Uses the Rounding Methods of the Math Class
- 3 Binary search
- 4 Compare Two Java double Arrays
- 5 Compute the value of 2/3 of 5
- 6 Convert from double to String
- 7 Convert from String to double
- 8 Converting a String to a double type Number
- 9 Convert java Double to numeric primitive data types
- 10 Convert Java String to Double
- 11 Create a Double object using one of the below given constructors
- 12 Double Array
- 13 Double class creates primitives that wrap themselves around data items of the double data type
- 14 Get Double Number
- 15 Gets the maximum of three double values.
- 16 Gets the minimum of three double values.
- 17 Get the next machine representable number after a number, moving in the direction of another number.
- 18 Java Double compare example
- 19 Java double: double is 64 bit double precision type and used when fractional precision calculation is required.
- 20 Java Double isInfinite
- 21 Java Double isNaN method
- 22 Linear Searching double Arrays
- 23 Min and Max values of data type double
- 24 Obtaining the integer and fractional parts
- 25 Returns the sign for double precision x
- 26 Show INFINITY and NaN
- 27 Ternary operator on double value
- 28 The Circle Area Calculator
- 29 Use Double constructor to convert double primitive type to a Double object.
- 30 Use toString method of Double class to convert Double into String.
A Program That Uses the Mathematical Methods of the Math Class
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));
}
}
A Program That Uses the Rounding Methods of the Math Class
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));
}
}
Binary search
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");
}
}
Compare Two Java double Arrays
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));
}
}
Compute the value of 2/3 of 5
/** 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);
}
}
Convert from double to String
public class Main {
public static void main(String[] args) throws Exception {
String str = Double.toString(23);
}
}
Convert from String to double
public class Main {
public static void main(String[] args) throws Exception {
Double d = Double.valueOf("0.9D").doubleValue();
}
}
Converting a String to a double type Number
public class Main {
public static void main(String[] argv) throws Exception {
double d = Double.parseDouble("123.4e10");
System.out.println(d);
}
}
Convert java Double to numeric primitive data types
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
*/
Convert Java String to Double
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);
}
}
Create a Double object using one of the below given constructors
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);
}
}
Double Array
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();
}
}
}
Double class creates primitives that wrap themselves around data items of the double data type
public class MainClass {
public static void main(String[] args) {
double d = 3.5;
Double d2 = new Double(d);
System.out.println(d2.doubleValue());
}
}
Get Double Number
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");
}
}
Gets the maximum of three double values.
/*
* 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Gets the maximum of three <code>double</code> values.</p>
*
* <p>If any value is <code>NaN</code>, <code>NaN</code> is
* returned. Infinity is handled.</p>
*
* @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);
}
}
Gets the minimum of three double values.
/*
* 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.
*/
/**
* <p>Provides extra functionality for Java Number classes.</p>
*
* @author
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/
public class Main {
/**
* <p>Gets the minimum of three <code>double</code> values.</p>
*
* <p>If any value is <code>NaN</code>, <code>NaN</code> is
* returned. Infinity is handled.</p>
*
* @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);
}
}
Get the next machine representable number after a number, moving in the direction of another number.
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.
* <p>
* If <code>direction</code> is greater than or equal to<code>d</code>,
* the smallest machine representable number strictly greater than
* <code>d</code> is returned; otherwise the largest representable number
* strictly less than <code>d</code> is returned.</p>
* <p>
* If <code>d</code> is NaN or Infinite, it is returned unchanged.</p>
*
* @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));
}
}
}
}
Java Double compare example
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("=");
}
}
}
Java double: double is 64 bit double precision type and used when fractional precision calculation is required.
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
Java Double isInfinite
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);
}
}
Java Double isNaN method
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);
}
}
Linear Searching double Arrays
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");
}
}
Min and Max values of data type double
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
*/
Obtaining the integer and fractional parts
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);
}
}
Returns the sign for double precision x
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 <code>x</code>.
* <p>
* For a double value <code>x</code>, this method returns
* <code>+1.0</code> if <code>x > 0</code>, <code>0.0</code> if
* <code>x = 0.0</code>, and <code>-1.0</code> if <code>x < 0</code>.
* Returns <code>NaN</code> if <code>x</code> is <code>NaN</code>.</p>
*
* @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;
}
}
Show INFINITY and NaN
/**
* 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");
}
//-
}
Ternary operator on double value
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"));
}
}
The Circle Area Calculator
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);
}
}
Use Double constructor to convert double primitive type to a Double object.
public class Main {
public static void main(String[] args) {
double d = 10.56;
Double dObj = new Double(d);
System.out.println(dObj);
}
}
Use toString method of Double class to convert Double into String.
public class Main {
public static void main(String[] args) {
Double dObj = new Double(10.25);
String str = dObj.toString();
System.out.println(str);
}
}