Alex Gittemeier
Alex Gittemeier

Reputation: 5373

Java Floating Point Math Mistake?

I am trying to calculate an aspect ratio for an image:

Log.d("img.width:", String.valueOf(img.getIntrinsicWidth()));
Log.d("img.height:", String.valueOf(img.getIntrinsicHeight()));
float aspect = ((float)img.getIntrinsicWidth()) / ((float)img.getIntrinsicWidth());
Log.d("aspect:", String.valueOf(aspect));

however this produces unexpected results:

img.width:   297
img.height:  167
aspect:      1.0

This seems like it has a simple answer, yet I can't figure it out.

Upvotes: 2

Views: 258

Answers (5)

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

You have a typo, you're dividing width by width. Should probably be width by height.

Also, to make it a bit easier on the eyes, you don't need to cast both sides for a division to use floats; the left side will be converted to float automatically if the right side is one.

float aspect = img.getIntrinsicWidth() / (float)img.getIntrinsicHeight();

Upvotes: 1

Churk
Churk

Reputation: 4637

have you try float aspect = (new float(img.getIntrinsicWidth())) / (new float(img.getIntrinsicWidth()));

Upvotes: 1

Hunter McMillen
Hunter McMillen

Reputation: 61540

You have a typo.

float aspect = ((float)img.getIntrinsicWidth()) / 
                                                ((float)img.getIntrinsicWidth());

You are dividing the width by the width, which will always produce 1, divide by the height instead:

float aspect = ((float)img.getIntrinsicWidth()) /
                                               ((float)img.getIntrinsicHeight());

Upvotes: 6

mbh
mbh

Reputation: 3312

Its a typo, one of them has to be height. You are dividing width by width

float aspect = ((float)img.getIntrinsicWidth()) / ((float)img.getIntrinsicWidth());

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799420

You're dividing width by width. Try substituting one of them with the height.

Upvotes: 8

Related Questions