T.Setso - 2 months ago 4x

Java Question

i have this piece of Code for the calc:

`public static double CalcPoisson(double m, double u, boolean va)`

{

double answer = 0;

if(!va)

{

answer = (Math.exp(-u)* Math.pow(u, m)) / (factorial(m));

}

if(va)

{

for(int i = 0; i < m; i++)

{

answer = answer + (Math.exp(-u)* Math.pow(u, i)) / (factorial(i));

}

}

return answer;

And this was my factorial method

`public static double factorial (double n)`

{

return n == 0 ? 1 : n *factorial(n-1);

}

Problem is: the maximum value to calculate is 170...i need way more (like factorial of 500)

I have written a new Method:

`public static BigDecimal factorial2 (double n)`

{

BigDecimal fct = BigDecimal.valueOf(1);

for(int i = 1; i<=n; i++)

{

fct = fct.multiply(BigDecimal.valueOf(i));

}

return fct;

How can i use my new factorialmethod in my "CalcPoisson" Method?

Problem is, i cant divide double with BigDecimal...

Thanks for the help :)

For No One:

I have still this Line of Code in one method that uses CalcPoisson, im still bad with BigDecimal, i cant handle it.

The Line:

`BigDecimal nenner = CalcPoisson(m, u, false) + (1-p) * CalcPoisson(m, u, true);`

Answer

```
for(int i = 0; i < m; i++)
{
answer = answer + (Math.exp(-u)* Math.pow(u, i)) / (factorial(i));
}
```

Note that this algorithm computes all factorials from 0 through m-1. Much faster and more accurate to factor that out:

```
long fact = 1;
for(int i = 0; i < m; i++) {
answer = answer + (Math.exp(-u)* Math.pow(u, i)) / fact;
fact *= (i+1);
}
```

then note that Math.exp(-u) is invariant in the loop, so extract it:

```
long fact = 1;
double eu = Math.exp(-u);
for(int i = 0; i < m; i++) {
answer = answer + (eu * Math.pow(u, i)) / fact;
fact *= (i+1);
}
```

And you can also get rid of the repeated calls to Math.pow():

```
long fact = 1;
double eu = Math.exp(-u);
double term = u;
for(int i = 0; i < m; i++) {
answer = answer + (eu * term) / fact;
fact *= (i+1);
term *= u;
}
```

Finally, you can also get combine term and fact into a single parameter (left as an exercise for the student).

Source (Stackoverflow)

Comments