This question already has answers here:
How to avoid floating point precision errors with floats or doubles in Java?
(12 answers)
Closed 5 years ago.
I have the following code.
public class ToBeDeleted {
public static final float MAX_PHYSICAL_LENGTH = 100000000;
public static void main(String[] args) {
//100000000
float temp = 100000000 -4;
System.out.println(temp);
if (MAX_PHYSICAL_LENGTH == temp)
System.out.println("True statement");
else
System.out.println("False Statement");
}
}
The output of the above is
1.0E8
True statement
Now with the below code
public class ToBeDeleted {
public static final float MAX_PHYSICAL_LENGTH = 100000000;
public static void main(String[] args) {
//100000000
float temp = 100000000 -5;
System.out.println(temp);
if (MAX_PHYSICAL_LENGTH == temp)
System.out.println("True statement");
else
System.out.println("False Statement");
}
}
The output is
9.9999992E7
False Statement
The question is
Whats wrong with the first code snip. Is this not plain mathematics
as far as float is concerned?
Why does it then give the expected output on the second code snip.
A typical (i.e. IEEE754) float only has 23 bits of precision. The other bits are for the exponent and the sign. The lowest integer that you can't store exactly is 1 plus the 24th power of 2.
100000000 - 4 is indistinguishable from 100000000 - 0.
A Java double gives you 52 bits of precision, therefore enough space to store all integers exactly up to the 53rd power of 2.
For more details see Which is the first integer that an IEEE 754 float is incapable of representing exactly?
But if you need exact decimal accuracy, then use a decimal type.
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 2 years ago.
I have the following method in a Java program:
public void Div(int a, int b){
//exception in order to check if the second argument is 0
try{
int div1 = (a / b);
double div = div1;
System.out.println("The division of the two numbers is: " + div);
}
catch(ArithmeticException e){
System.out.println("You can't divide a number by 0");
}
This only works if numerator is larger than the denominator ( e.g 8/2). If the numerator is smaller than the denominator I get a result of 0.0 (e.g. 2/8).
What can I do to make it work?
It's happening because of integer division. You can cast one of the arguments to double and store the result to a double variable to fix the issue.
public class Main {
public static void main(String[] args) {
div(5, 10);
}
public static void div(int a, int b) {
try {
double div = (double) a / b;
System.out.println("The division of the two numbers is: " + div);
} catch (ArithmeticException e) {
System.out.println("You can't divide a number by 0");
}
}
}
Output:
The division of the two numbers is: 0.5
On a side note, you should follow Java naming conventions e.g. the method name, Div should be div as per the Java naming conventions.
(a/b) You're doing integer division. You need to typecast to other data types that can store decimal like double.
double div = (double) a / b;
This question already has answers here:
How Does Modulus Divison Work
(19 answers)
Closed 5 years ago.
package PracticePackage;
public class whileLoop {
public static void main(String[] args) {
int i=1;
System.out.println("Quotient "+i/2);
System.out.println("Remainder "+i%2);
}
}
this is the fomula that Java uses to yield the remainder of its operands:
(a/b)*b+(a%b)
where a is the dividend and b is the divisor.
so in your case it's like:
int i = 1;
int b = 2;
int result = (i / b) * b + (i % b);
hence the result 1 rather than 0
1/2 = 0.5
you defined i as int
Integral division in java takes floor of the answer if the answer is a real number so 1/2 becomes 0, making 1%2 equal to 1
I hope that explains.
because integers are not real numbers so you get 1 as answer and the real part of remainder is ignored since you defined i as an integer
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
/**
* Write a description of class GUI here.
*
* #author (your name)
* #version (a version number or a date)
*/
import java.util.*;
public class GUI
{
// instance variables - replace the example below with your own
public static void main(String [] args){
Scanner r = new Scanner(System.in);
int x;
int y;
int z;
System.out.println("x");
x = r.nextInt();
System.out.println("y");
y = r.nextInt();
System.out.println("z");
z = r.nextInt();
double t = (x+y+z)/3;
System.out.println("result " + t);
}
}
Hello, above is my code.
I purposely made it int x,y,z to test the program.
When I input for example (when running the program) :$x = 1, 1, 3$ it rounds the answer always! Why is this?
This is an example of Java's integer division, which must always return another integer. It truncates any decimal result. This occurs even though the result is assigned to a double.
Use a double literal when dividing to force floating-point division.
double t = (x+y+z)/3.0;
This question already has answers here:
Is floating point math broken?
(31 answers)
Strange floating-point behaviour in a Java program [duplicate]
(4 answers)
Closed 4 years ago.
I want a create a array of values with a interval of 0.2
I used the code :
public class TrialCode {
public static void main(String[] args) {
float a = -1.0f, b = 0.2f;
for (int i = 0; i <10; i++) {
a = a + b;
System.out.println(a);
}
}
}
Now the output that i am getting is :
-0.8
-0.6
-0.40000004
-0.20000003
-2.9802322E-8
0.19999997
0.39999998
0.59999996
0.79999995
0.99999994
whereas the output I want is
-0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1.0
What should I do ?
If you don't want floating-point arithmetic, then don't use floating-point types. Float and Double aren't the only non-integral Numbers in the Java core library. What you're doing calls for BigDecimal.
import java.math.BigDecimal;
public class TrialCode {
public static void main(String[] args) {
BigDecimal a = new BigDecimal("-1.0");
BigDecimal b = new BigDecimal("0.2");
for (int i = 0; i < 10; i++) {
a = a.add(b);
System.out.println(a);
}
}
}
Floating point numbers only work up to a certain precision. For float it is 6-7 significant digits, for double it is 15-16 significant digits. And due to the binary representation simple decimal fractions like 0.1 cannot be represented exactly.
You can round the output to get the results you want:
System.out.printf("%.1f", a);
You can use something like
new DecimalFormat("#.#").format(0.19999997); //"0.2"
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
I have tried this in Javascript and have gotten my answers, but the answer I need must be more exact. I am trying to divide 1 by every number between 2 and 1000, and simply print them.
public static void main(String [] args) {
for (int i=2;i<=1000;i++){
double g = (1/i);
System.out.println(g); // print "1/1,2,3,4.....1000"
}
}
I haven't done Java in a while, so I forget my correct variable names.
Since both 1 and i are integers, integer division is being used. Either 1 or i need to be double in the 1/i section of your code so that integer division is not used. You can do something like 1.0/i or 1/((double) i) to ensure that float division is used instead.
replace 1 by 1.0D that will result into double
try this
public static void main ( String args[] ) {
for (int i=2;i<=1000;i++){
double g = (1.0/i);
System.out.println("1/"+ig);
}
output:
0.5
0.3333333333333333
0.25
0.2
0.16666666666666666
0.14285714285714285
0.125
.
.
.
.
I would do something like this (note you can have as many digits of precision as you like) utilizing BigDecimal.
public static void main(String[] args) {
java.math.BigDecimal ONE = java.math.BigDecimal.ONE;
// 50 digits of precision.
java.math.MathContext mc = new java.math.MathContext(50);
for (int i = 2; i <= 1000; i++) {
java.math.BigDecimal divisor = new java.math.BigDecimal(i);
java.math.BigDecimal result = ONE.divide(divisor, mc);
result.round(mc);
System.out.printf("%d/%d = %s\n", 1, i,
result.toString());
}
}