Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing two integers to a double in java

I can see this is a common problem for new programmers, however I didn't succeed in implementing any of the solution to my code. Basically I want to divide w and v, which must be saved to a double variable. But it prints [0.0, 0.0, ... , 0.0]

public static double density(int[] w, int[] v){
double d = 0;
    for(L = 0; L < w.length; L++){
        d = w[L]  /v[L];
    }
    return d;
}
like image 491
roarknuppel Avatar asked Sep 30 '13 09:09

roarknuppel


3 Answers

This line here d = w[L] /v[L]; takes place over several steps

d = (int)w[L]  / (int)v[L] d=(int)(w[L]/v[L])            //the integer result is calculated d=(double)(int)(w[L]/v[L])    //the integer result is cast to double 

In other words the precision is already gone before you cast to double, you need to cast to double first, so

d = ((double)w[L])  / (int)v[L]; 

This forces java to use double maths the whole way through rather than use integer maths and then cast to double at the end

like image 191
Richard Tingle Avatar answered Sep 22 '22 14:09

Richard Tingle


use like following

    d = (double) w[L]  /v[L]; 
like image 32
stinepike Avatar answered Sep 25 '22 14:09

stinepike


Actaully w[L]/v[L] here both are integers. On the division operation it lost precision and truncated to integer value. Then the truncated integer is converted to double.

The solution would be convert the operand or the divisor or both to a double. Then the division operation would produce a double.

d = w[L]/(double)v[L];
like image 38
Subhrajyoti Majumder Avatar answered Sep 24 '22 14:09

Subhrajyoti Majumder