Matt Martin
Matt Martin

Reputation: 855

Java- double variable issue

Here's my simple equations counter.Now it counts equations with two variables.It's based on trying many combinations (4 milion or 16 milion) of a and b variables.So the code works well and it counts exact.But since I tried to change variable b to double, things go wrong.I've expected line b=b+0.1 secures setting variable b each 10th time to 1.0.But almost imidiately after start way more decimal numbers appear for each b.So do I use wrong datatype? Or should I raise variable b by different value?(I also tried changing all variables to double).Thank you for suggestions!

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Buffer{
static int a;
static double b;
static BufferedReader reader;
static String query;
static int range;
static int result;

public static void main(String[] args)throws IOException{
    reader=new BufferedReader(new InputStreamReader(System.in));

    System.out.print("Choose speed of test(fast or slow):");
    query=reader.readLine();

    if(query.equals("fast"))
        range=2000;
    else
        range=4000;

     //START THE TEST//       
    while((a+b)!=26000){
        b=b+0.1;
        if(b==range+1){
            b=0;
            a=a+1;
        }
        if((a+b)!=26000)
            System.out.println("a- "+a+", "+"b- "+b+"=false.");

        if((a+b)==26000){
            System.out.println("a- "+a+", "+"b- "+b+"=true.");
            System.out.println("\n"+"Done.You can possibly solve this equation, if a= "+a+" and b= "+b+".");
        }
        if(a==range&&b==range&&(a+b)!=26000){
            System.out.println("\n"+"Tested "+a*b+" options.Solution not found.");
            System.exit(0);
        }
    }   
}
}

Upvotes: 1

Views: 1456

Answers (3)

JNL
JNL

Reputation: 4713

Everyone here, did give you an alternative solution, but I think you should understand, why did the datatype double did not work for you.

The problem lies with Binary representation. For decimals is not represented to the exact form. Say for example:

10 is represented as 1010 in binary but,

0.10 is 0.00011001100110011001100110011001 and still going on.....

Hence the error occurs in double. As suggested by others, opt for BigDecimal.

You can also learn more about the same, through these links;

Rounding Errors

Addition Of Doubles

Hope that helps.

Upvotes: 1

marderh
marderh

Reputation: 1256

You can use BigDecimal instead of float/double primitives to avoid those issues. Some of which are described here: Java Mistake 1 - Using float and double for monetary or financial calculation

Upvotes: 5

The issue you deal with is representation error. Type double can not represent some values.

Typical solution for this situation is usage of BigDecimal or Integer type.

Upvotes: 1

Related Questions