Re: frustrating arithmetic
- From: "Rhino" <no.offline.contact.please@xxxxxxxxxx>
- Date: Tue, 27 Dec 2005 14:34:07 -0500
"Jonie" <kimfinale@xxxxxxxxx> wrote in message
news:1135706796.960141.141240@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> hi all,
> i am looking forward to finding someone who could help me out. from
> the following code,
> i get 45 for the variable "numSusceptible" and 50 for "numNode". and
> then i get 5 for "(numNodes - numSusceptible)". however, i get zero
> when i calculate "(numNodes - numSusceptible) / numNodes". i don't
> understand what is going on here. I would appreciate it if anyone
> could help me understand. many thanks in advance.
>
>
>
> private void getPrevalence() {
> double prevalence = 0;
> int numSusceptible = 0;
> String string;
> for (int i = 0; i < numNodes; i++) {
> GayNode iNode = (GayNode) agentList.get(i);
> string = iNode.getInfectStatus();
> System.out.printf("status = %s ", string);
> if (string.equals("s")) {
> numSusceptible += 1;
> }
> }
> prevalence = (numNodes - numSusceptible) / numNodes;
> System.out.printf("\nSusceptibles = %d ", numSusceptible);
> System.out.printf("numNodes = %d ", numNodes);
> System.out.printf("prevalence =%.4f \n", prevalence);
> //return prevalence;
> }I
>
Your problem is that Java is doing integer arithmetic when you expect it to
do decimal arithmetic.
When you see the equation:
prevalence = (50- 45) /50;
you expect Java to evaluate it as:
prevalence = 5/50;
prevalance = 0.1;
But Java actually sees 5/50 as an _integer_ expression so it gives you 0
because 0 is the integer that is closest to the value of 5/50. That probably
seems odd because you've defined prevalence as being a double so you expect
the result to be 0.1 but this is the way Java works by default.
If you want Java to use decimal arithmetic, you need to write something like
this:
prevalence = ((double) (numNodes - numSusceptible))/((double) numNodes);
In this version of the statement, the expression (numNodes -
numSusceptible), which is an integer since both variables are integers,
gives an integer result but the '(double)' that precedes the expression
casts (converts) the integer result to a double; thus, 5 turns into 5.0.
Also, the '(double)'
that prededes numNodes in the denominator casts 50 to 50.0. When you divide
5.0 by 50.0, the result is the double value 0.1, not the integer value 0.
If you don't like using casts, the other option you have is to make the
variables numNodes and numSusceptible doubles instead of ints; then you
won't need the casts and your expression to calculate prevalence doesn't
need to change at all.
Rhino
.
- References:
- frustrating arithmetic
- From: Jonie
- frustrating arithmetic
- Prev by Date: Re: Suduko solver demo
- Next by Date: Re: frustrating arithmetic
- Previous by thread: frustrating arithmetic
- Next by thread: Re: frustrating arithmetic
- Index(es):
Relevant Pages
|