Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Possible loss of precision" in my Java program

Tags:

java

I'm new to Java. I wrote the following code:

import java.io.*;
import java.lang.*;

public class distravel
{
    public static void main(String args[])
    {
        String a1,a2,a3;
        int x=2;
        float d,u,a,t;
         //d=distance travelled,u=initial velocity,a=acceleration,t=timeinterval

        try
        {
            InputStreamReader read=new InputStreamReader(System.in);
            BufferedReader buff=new BufferedReader(read);

            System.out.print("Enter the INTIAL VELOCITY:");
            a1=buff.readLine();
            u=Float.parseFloat(a1);
            System.out.print("Enter the ACCELERATION:");
            a2=buff.readLine();
            a=Float.parseFloat(a2);
            System.out.print("Enter the TIME:");
            a3=buff.readLine();
            t=Float.parseFloat(a3);

            d=((u*t)+a*Math.pow(t,x))/2F;

            System.out.print("The total DISTANCE TRAVELLED:"+d);
        }
        catch(Exception e)
        {}
    }
}

I get this error:

distravel.java28:possible loss of precision
                                   found           :double
                                   required        :float
                                   d=((u*t)+a*Math.pow(t,x))/2F;
                                                            ^

How can I resolve this?

like image 923
DEEPAK_MANRAL Avatar asked Apr 09 '11 06:04

DEEPAK_MANRAL


4 Answers

d=((u*t)+a*Math.pow(t,x))/2F;

should be

d=(float)((u*t)+a*Math.pow(t,x))/2F;

or declare d as double as GrahamS suggested.

like image 195
Prince John Wesley Avatar answered Nov 18 '22 08:11

Prince John Wesley


Don't use floats in your floating point math calculations unless you have a specific reason for doing so (you don't). The overhead for the preferred type, double, is not much higher and the benefit in accuracy is great.

like image 43
Hovercraft Full Of Eels Avatar answered Nov 18 '22 10:11

Hovercraft Full Of Eels


Math.pow returns double so you have to have double for 'd'. Or you could also cast 'd' to float.

like image 3
Shankar Raju Avatar answered Nov 18 '22 08:11

Shankar Raju


It is because Math.pow() returns a double which you then do some calculations with. No matter what calculations you do the precision you will have to deal with is double. Therefore, you get the error message. Solutions:
1) make the floats double
2) cast the result to float: d=(float)((u*t)+a*Math.pow(t,x))/2F;

like image 2
jallmer Avatar answered Nov 18 '22 10:11

jallmer