0

I am trying to return a double from this int division. I read this question but I cant seem to make it work for this particular case:

yComponent +=
        ((Math.min(i.getObservedIndividuals(), ii.getObservedIndividuals()))/
        Math.max(i.getObservedIndividuals(), ii.getObservedIndividuals())*
        i.getObservedIndividuals())/
        (parent.getShareableSpecies()*
        match.getTotalObservedIndividuals());

yComponent is a double and everything else is int.

Community
  • 1
  • 1
Alexander
  • 480
  • 2
  • 5
  • 21
  • It doesn't matter what `yComponent` is, it's not part of the quotient. What is the type of `i.getObservedIndividuals()`? – Makoto Nov 19 '15 at 01:42
  • 1
    You probably need a cast to double in there. It's probably doing integer division but I didn't read it close. – shawnt00 Nov 19 '15 at 01:44
  • @shawnt00 I know this is integer division and its returning 0.00. I tried some casting but nothing. It is still returning 0.00 somehow. – Alexander Nov 19 '15 at 01:46
  • Why all the extra parentheses when everything's division/multiplication? They make things hard to read. – Steve K Nov 19 '15 at 01:47
  • @SteveK It makes it easier to me to show what belongs where. I've just always done it this way (specially when its a long formula). – Alexander Nov 19 '15 at 01:49
  • @Alexander An easier way to make it easier to read is to introduce named identifiers for your mid calculations ie: `int minIndividuals = Math.min(i.getObservedIndividuals(), ii.getObservedIndividuals()); int maxIndividuals = Math.max(i.getObservedIndividuals(), ii.getObservedIndividuals()); int percentPopulation = minIndividuals / maxIndividuals * i.getObservedIndividuals();` etc. Yes, it's more lines of code, but it's a hell of a lot easier to understand what the intention of your calculation is, and to make sure the steps are correct. – Steve K Nov 19 '15 at 02:10
  • Might help if you gave us actual numbers to work with or at least the value you expect to get. – shawnt00 Nov 19 '15 at 02:11
  • Also, @shawnt00 is correct; if the numbers are too close, when the integer division happens, if the number rounds down to less than 0.5, it will return 0. You need to use floats when doing division. – Steve K Nov 19 '15 at 02:15

1 Answers1

1
yComponent +=
    ((Math.min(i.getObservedIndividuals(), ii.getObservedIndividuals())) /
    (double) Math.max(i.getObservedIndividuals(), ii.getObservedIndividuals())*
    i.getObservedIndividuals()) /
    (double) (parent.getShareableSpecies()*
    match.getTotalObservedIndividuals());

A division won't use the "float processor" (arithmetic processor) if you don't cast at least one operand as a double or float. Which means that 3 / 2 = 1 for a CPU, but 3 / 2f = 1.5f

Guillaume F.
  • 4,271
  • 1
  • 23
  • 50