Java/Data Type/float
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Check if a string is a valid number
- 2 Clones a two dimensional array of floats.
- 3 Compares two floats for order.
- 4 Compare Two Java float Arrays
- 5 convert Fahrenheit to Celsius back and forth with float
- 6 Convert from float to String
- 7 Convert from String to float
- 8 Converting a String to a float type Number
- 9 Convert Java Float to Numeric Primitive Data Types
- 10 Convert Java String to Float Object
- 11 Float class creates primitives that wrap themselves around data items of the float data type
- 12 Float compare to
- 13 Float Double Time
- 14 Floating pioint comparisons
- 15 Floating-point comparisons
- 16 Floating-point error diagnostics
- 17 Floating�Point Types
- 18 Gets the maximum of three float values.
- 19 Gets the minimum of three float values.
- 20 Java Float Comparison
- 21 Java float is 32 bit single precision type and used when fractional precision calculation is required.
- 22 Java Float isInfinite Method
- 23 Java Float isNaN Method
- 24 Java Float Wrapper Class
- 25 Min and Max values of data type float
- 26 Pass floats as string literals to a method
- 27 Returns the sign for float value x
- 28 Use Float constructor to convert float primitive type to a Float object.
- 29 Use toString method of Float class to convert Float into String.
Check if a string is a valid number
public class Main {
public static void main(String[] argv) throws Exception {
String age = "1";
String height = "1.5";
String weight = "5.9";
int theAge = Integer.parseInt(age);
float theHeight = Float.parseFloat(height);
double theWeight = Double.parseDouble(weight);
System.out.println("Age: " + theAge);
System.out.println("Height: " + theHeight);
System.out.println("Weight: " + theWeight);
}
}
Clones a two dimensional array of floats.
/*
* JCommon : a free general purpose class library for the Java(tm) platform
*
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* -------------------
* ArrayUtilities.java
* -------------------
* (C) Copyright 2003-2005, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: ArrayUtilities.java,v 1.7 2008/09/10 09:21:30 mungady Exp $
*
* Changes
* -------
* 21-Aug-2003 : Version 1 (DG);
* 04-Oct-2004 : Renamed ArrayUtils --> ArrayUtilities (DG);
*
*/
public class Main {
/**
* Clones a two dimensional array of floats.
*
* @param array the array.
*
* @return A clone of the array.
*/
public static float[][] clone(final float[][] array) {
if (array == null) {
return null;
}
final float[][] result = new float[array.length][];
System.arraycopy(array, 0, result, 0, array.length);
for (int i = 0; i < array.length; i++) {
final float[] child = array[i];
final float[] copychild = new float[child.length];
System.arraycopy(child, 0, copychild, 0, child.length);
result[i] = copychild;
}
return result;
}
}
Compares two floats for order.
/*
* 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>Compares two floats for order.</p>
*
* <p>This method is more comprehensive than the standard Java greater than,
* less than and equals operators.</p>
* <ul>
* <li>It returns <code>-1</code> if the first value is less than the second.
* <li>It returns <code>+1</code> if the first value is greater than the second.
* <li>It returns <code>0</code> if the values are equal.
* </ul>
*
* <p> The ordering is as follows, largest to smallest:
* <ul>
* <li>NaN
* <li>Positive infinity
* <li>Maximum float
* <li>Normal positive numbers
* <li>+0.0
* <li>-0.0
* <li>Normal negative numbers
* <li>Minimum float (<code>-Float.MAX_VALUE</code>)
* <li>Negative infinity
* </ul>
*
* <p>Comparing <code>NaN</code> with <code>NaN</code> will return
* <code>0</code>.</p>
*
* @param lhs the first <code>float</code>
* @param rhs the second <code>float</code>
* @return <code>-1</code> if lhs is less, <code>+1</code> if greater,
* <code>0</code> if equal to rhs
*/
public static int compare(float lhs, float rhs) {
if (lhs < rhs) {
return -1;
}
if (lhs > rhs) {
return +1;
}
//Need to compare bits to handle 0.0 == -0.0 being true
// compare should put -0.0 < +0.0
// Two NaNs are also == for compare purposes
// where NaN == NaN is false
int lhsBits = Float.floatToIntBits(lhs);
int rhsBits = Float.floatToIntBits(rhs);
if (lhsBits == rhsBits) {
return 0;
}
//Something exotic! A comparison to NaN or 0.0 vs -0.0
//Fortunately NaN"s int is > than everything else
//Also negzeros bits < poszero
//NAN: 2143289344
//MAX: 2139095039
//NEGZERO: -2147483648
if (lhsBits < rhsBits) {
return -1;
} else {
return +1;
}
}
}
Compare Two Java float Arrays
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
float[] a1 = new float[] { 4.4f, 3.3f, 5.3f };
float[] a2 = new float[] { 4.4f, 3.3f, 5.3f };
System.out.println(Arrays.equals(a1, a2));
}
}
convert Fahrenheit to Celsius back and forth with float
public class Weather {
public static void main(String[] arguments) {
float fah = 86;
System.out.println(fah + " degrees Fahrenheit is ...");
fah = fah - 32;
fah = fah / 9;
fah = fah * 5;
System.out.println(fah + " degrees Celsius\n");
float cel = 33;
System.out.println(cel + " degrees Celsius is ...");
cel = cel * 9;
cel = cel / 5;
cel = cel + 32;
System.out.println(cel + " degrees Fahrenheit");
}
}
Convert from float to String
public class Main {
public static void main(String[] args) throws Exception {
String str = Float.toString(0.3F);
}
}
Convert from String to float
public class Main {
public static void main(String[] args) throws Exception {
Float f = Float.valueOf("0.2").floatValue();
}
}
Converting a String to a float type Number
public class Main {
public static void main(String[] argv) throws Exception {
float f = Float.parseFloat("123.4");
System.out.println(f);
}
}
Convert Java Float to Numeric Primitive Data Types
public class Main {
public static void main(String[] args) {
Float fObj = new Float("10.50");
byte b = fObj.byteValue();
System.out.println(b);
short s = fObj.shortValue();
System.out.println(s);
int i = fObj.intValue();
System.out.println(i);
float f = fObj.floatValue();
System.out.println(f);
double d = fObj.doubleValue();
System.out.println(d);
}
}
Convert Java String to Float Object
public class Main {
public static void main(String[] args) {
Float fObj1 = new Float("10.64");
System.out.println(fObj1);
Float fObj2 = Float.valueOf("10.76");
System.out.println(fObj2);
float f = Float.parseFloat("7.39");
System.out.println(f);
}
}
/*
10.64
10.76
7.39
*/
Float class creates primitives that wrap themselves around data items of the float data type
public class MainClass {
public static void main(String[] args) {
float f = -29.6f;
Float f2 = new Float(f);
System.out.println(f2.floatValue());
}
}
Float compare to
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
public class NumberDemo {
public static void main(String args[]) {
Float one = new Float(14.78f - 13.78f);
Float oneAgain = Float.valueOf("1.0");
Double doubleOne = new Double(1.0);
int difference = one.rupareTo(oneAgain);
if (difference == 0) {
System.out.println("one is equal to oneAgain.");
} else if (difference < 0) {
System.out.println("one is less than oneAgain.");
} else if (difference > 0) {
System.out.println("one is greater than oneAgain.");
}
System.out.println("one is "
+ ((one.equals(doubleOne)) ? "equal" : "not equal")
+ " to doubleOne.");
}
}
Float Double Time
public class FloatDoubleTime {
/** How many times to do the loop */
protected static final int HOW_MANY = 10000000;
public static void main(String[] args) {
long t0 = System.currentTimeMillis();
float f = 0;
for (int i=0; i<HOW_MANY; i++)
f *= i;
long t1 = System.currentTimeMillis();
double d = 0;
for (int i=0; i<HOW_MANY; i++)
d *= i;
long t2 = System.currentTimeMillis();
System.out.println("Float: " + (t1 - t0) + " " + f);
System.out.println("Double: " + (t2 - t1) + " " + d);
}
}
Floating pioint comparisons
class MainClass {
public static void main(String[] args) {
double num1 = -0.0;
double num2 = 0.0;
double sqrPos = Math.sqrt(4.0);
double sqrNeg1 = Math.sqrt(-4.0);
double sqrNeg2 = Math.sqrt(-9.0);
System.out.println("Using == to compare 0.0 and -0.0 ");
if (num1 == num2)
System.out.println("numbers are equal");
else
System.out.println("numbers are not equal");
Double n1 = new Double(num1);
Double n2 = new Double(num2);
System.out.println("Using equals() method to compare 0.0 and -0.0 ");
if (n1.equals(n2))
System.out.println("numbers are equal");
else
System.out.println("numbers are not equal");
Double sp1 = new Double(sqrPos);
Double sn1 = new Double(sqrNeg1);
Double sn2 = new Double(sqrNeg2);
System.out.println("Using equals() method to compare two NaNs ");
if (sn1.equals(sn2))
System.out.println("NaNs are equal");
else
System.out.println("NaNs are not equal");
}
}
Floating-point comparisons
/**
* Floating-point comparisons.
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: FloatCmp.java,v 1.11 2004/02/09 03:33:56 ian Exp $
*/
public class FloatCmp {
final static double EPSILON = 0.0000001;
public static void main(String[] argv) {
double da = 3 * .3333333333;
double db = 0.99999992857;
// Compare two numbers that are expected to be close.
if (da == db) {
System.out.println("Java considers " + da + "==" + db);
// else compare with our own equals method
} else if (equals(da, db, 0.0000001)) {
System.out.println("True within epsilon " + EPSILON);
} else {
System.out.println(da + " != " + db);
}
// Show that comparing two NaNs is not a good idea:
double d1 = Double.NaN;
double d2 = Double.NaN;
if (d1 == d2)
System.err.println("Comparing two NaNs incorrectly returns true.");
if (!new Double(d1).equals(new Double(d2)))
System.err.println("Double(NaN).equal(NaN) incorrectly returns false.");
}
/** Compare two doubles within a given epsilon */
public static boolean equals(double a, double b, double eps) {
if (a==b) return true;
// If the difference is less than epsilon, treat as equal.
return Math.abs(a - b) < eps;
}
/** Compare two doubles, using default epsilon */
public static boolean equals(double a, double b) {
if (a==b) return true;
// If the difference is less than epsilon, treat as equal.
return Math.abs(a - b) < EPSILON * Math.max(Math.abs(a), Math.abs(b));
}
}
Floating-point error diagnostics
/*
Java Programming for Engineers
Julio Sanchez
Maria P. Canton
ISBN: 0849308100
Publisher: CRC Press
*/
// Java for Engineers
//Filename: FpError
//Reference: Chapter 24
//Description:
// Floating-pioint error diagnostics
//Requires:
// Keyin class in current directory
class FpError {
public static void main(String[] args) {
double res;
double divisor = 0;
double dividend, root;
// Get user input for numerator
System.out.println("Forcing division by zero error");
dividend = 10d;
res = dividend / divisor;
// Test for negative invifinity
if (res == Double.NEGATIVE_INFINITY)
System.out.println("result is NEGATIVE_INFINITY");
if (res == Double.POSITIVE_INFINITY)
System.out.println("result is POSITIVE_INFINITY");
// Test for either infinity
if (Double.isInfinite(res))
System.out.println("result is infinite");
// Get user input for square root
System.out.println("\nCalculating square root (try negative)");
root = 10d;
res = Math.sqrt(root);
if (Double.isNaN(res))
System.out.println("result is Nan");
else
System.out.println("Square root = " + res);
}
}
Floating�Point Types
public class Main {
public static void main(String[] args) {
double pi = 3.14159;
float f = 2.2F;
System.out.println("pi = " + pi);
System.out.println("f = " + f);
int n = 15, d = 4;
f = n / d;
System.out.println("15/4 = " + f);
int radius = 10;
double area = pi * radius * radius;
System.out.println("area = " + area);
}
}
Gets the maximum of three float 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>float</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(float, float, float) for a version of this method that handles NaN differently
*/
public static float max(float a, float b, float c) {
return Math.max(Math.max(a, b), c);
}
}
Gets the minimum of three float 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>float</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(float, float, float) for a version of this method that handles NaN differently
*/
public static float min(float a, float b, float c) {
return Math.min(Math.min(a, b), c);
}
}
Java Float Comparison
public class Main {
public static void main(String[] args) {
float f1 = 5.5f;
float f2 = 5.4f;
int i1 = Float.rupare(f1, f2);
if (i1 > 0) {
System.out.println(">");
} else if (i1 < 0) {
System.out.println("<");
} else {
System.out.println("=");
}
Float fObj1 = new Float("5.5");
Float fObj2 = new Float("5.4");
int i2 = fObj1.rupareTo(fObj2);
if (i2 > 0) {
System.out.println(">");
} else if (i2 < 0) {
System.out.println("<");
} else {
System.out.println("=");
}
}
}
Java float is 32 bit single precision type and used when fractional precision calculation is required.
public class Main {
public static void main(String[] args) {
float f = 12.3f;
System.out.println("Value of float variable f is :" + f);
}
}
//Value of float variable f is :12.3
Java Float isInfinite Method
public class Main {
public static void main(String[] args) {
float f = (float) 1 / 0;
boolean b1 = Float.isInfinite(f);
System.out.println(b1);
Float fObj = new Float(f);
boolean b2 = fObj.isInfinite();
System.out.println(b2);
}
}
Java Float isNaN Method
public class Main {
public static void main(String[] args) {
float f = (float) Math.sqrt(-10);
boolean b1 = Float.isNaN(f);
System.out.println(b1);
Float fObj = new Float(f);
boolean b2 = fObj.isNaN();
System.out.println(b2);
}
}
Java Float Wrapper Class
public class Main {
public static void main(String[] args) {
float f = 10.10f;
Float fObj1 = new Float(f);
System.out.println(fObj1);
double d = 10.10;
Float fObj2 = new Float(d);
System.out.println(fObj2);
Float fObj3 = new Float("25.34");
System.out.println(fObj3);
}
}
Min and Max values of data type float
public class Main {
public static void main(String[] args) {
System.out.println(Float.MIN_VALUE);
System.out.println(Float.MAX_VALUE);
}
}
/*
1.4E-45
3.4028235E38
*/
Pass floats as string literals to a method
public class Main {
public static void main(String[] argv) {
System.out.println(0.1f);
}
}
Returns the sign for float value 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 float value <code>x</code>.
* <p>
* For a float value x, this method returns +1.0F if x > 0, 0.0F if x =
* 0.0F, and -1.0F if x < 0. Returns <code>NaN</code> if <code>x</code>
* is <code>NaN</code>.</p>
*
* @param x the value, a float
* @return +1.0F, 0.0F, or -1.0F, depending on the sign of x
*/
public static float sign(final float x) {
if (Float.isNaN(x)) {
return Float.NaN;
}
return (x == 0.0F) ? 0.0F : (x > 0.0F) ? 1.0F : -1.0F;
}
}
Use Float constructor to convert float primitive type to a Float object.
public class Main {
public static void main(String[] args) {
float f = 10.56f;
Float fObj = new Float(f);
System.out.println(fObj);
}
}
Use toString method of Float class to convert Float into String.
public class Main {
public static void main(String[] args) {
Float fObj = new Float(10.25);
String str = fObj.toString();
System.out.println(str);
}
}