Reputation: 33
I am trying compute average of two double value, but it dose not work truly. I think it is "rounding error" am I right? and how can I fix it?
point.get(0)=1
point.get(1)=4
double Average = (double)(point.get(0) + point.get(1) / 2);
Output:
Average: 3.0
Why?
Upvotes: 0
Views: 2204
Reputation: 1
Division takes precedence over addition. Hence,
Average = (double)(1 + 4/2) = (double) (1+2) = 3.0
You should probably make it more like
Average = (double)((1+4)/2)
Upvotes: 0
Reputation: 7511
This has to do with the order of operators - the /
has a higher precedence than +
, so you are actually getting 1 + (4/2) which does equal 3.
Try this instead:
double Average = (double)((point.get(0) + point.get(1)) / 2);
The extra brackets will correct your issue.
Upvotes: 0
Reputation: 310915
double Average = (double)(point.get(0) + point.get(1) / 2)
Operator precedence trouble. Try this:
double Average = (point.get(0) + point.get(1)) / 2.0;
Upvotes: 1
Reputation: 68715
double Average = (double)(point.get(0) + point.get(1) / 2);
is executed as
Average = (double)(1 + 4/2) = (double) (1+2) = 3.0
Problem
Divison(/) has higher precedence than addition(+)
Fix
You need to add brackets for proper calculation:
double Average = (double)((point.get(0) + point.get(1)) / 2);
should execute as:
Average = (double)((1 + 4)/2) = (double) (5/2) = 2.5
Upvotes: 7