Reputation: 1502
public static int NUM_FRAMES = 8;
public static int FRAME_REPEAT_NO = 2;
int height = 24;
//bitmap.getWidth() is 168 and bitmap.getHeight() is 91
double w = bitmap.getWidth();
w = w/NUM_FRAMES;
w = w*FRAME_REPEAT_NO;
w = w*height;
w = w/bitmap.getHeight();
I do this and i get the value of w
as 11.07 which is correct.
But when i do this:
double w = FRAME_REPEAT_NO*(bitmap.getWidth()/NUM_FRAMES)*(height/bitmap.getHeight());
value of w
is always 0;
Can someone explain to me why this is happening?
P.S. I'm doing it in an android app...
Upvotes: 0
Views: 293
Reputation:
Others have already addressed your question, so I won't repeat their answers, but one suggestion I'll make. Consider computing your result using
w = (double)(FRAME_REPEAT_NO * bitmap.getWidth() * height) / (double)(NUM_FRAMES * bitmap.getHeight())
This allows you to live in the predictable land of integers until the very end where you do the division. So any error in the result comes from a single operation instead of aggregating multiple errors. And if for whatever reason you decided you wanted to get an integer result, you can drop the doubles and still get 11 as the answer.
Not a big deal but just thought I'd put it out there.
EDIT: I saw from your comment on another post that you actually want the 11. Good. So just drop the doubles altogether:
w = (FRAME_REPEAT_NO * bitmap.getWidth() * height) / (NUM_FRAMES * bitmap.getHeight())
Answer is exactly 11 (integer), which is different by the way than the floating point approximation of 11.0.
Upvotes: 0
Reputation: 34031
You're using integer arithmetic in a situation that requires floating point arithmetic:
double w = FRAME_REPEAT_NO*(bitmap.getWidth()/NUM_FRAMES)*(height/bitmap.getHeight());
// w = 2 * (168 / 8 ) * ( 24 / 91);
// w = 2 * (21 ) * ( 0 );
// w = 0;
As @JigarJoshi pointed out, the solution is to make sure you use floating point arithmetic. You can cast as per his suggestion, or you can do something like this:
public static float NUM_FRAMES = 8.0f;
public static float FRAME_REPEAT_NO = 2.0f;
float height = 24.0f;
float w = FRAME_REPEAT_NO * (bitmap.getWidth() / NUM_FRAMES) *
(height / bitmap.getHeight());
Upvotes: 1
Reputation: 33534
Follow the BODMAS RULE... I got the desired output using this rule...
Highest to Lowest priority..
B - Brackets
O - Power
DM - Divison and Multiplication
AS - Addition and Substraction
w = ((w/NUM_FRAMES)*(FRAME_REPEAT_NO)*(height))/bitmap.getHeight();
Output:
11.076923076923077
Upvotes: 0
Reputation: 240898
Cast int
to double
double w = FRAME_REPEAT_NO*(bitmap.getWidth()/((double)NUM_FRAMES))*(height/((double)bitmap.getHeight()));
Upvotes: 1