from VB to Java Factorial Method - java

In VBA code, here is the loop:
For i = 0 To 50
sum = sum + Exp(-lambda * T) * (lambda * T) ^ i / Application.Fact(i) * X
Next
In Java I converted to code like this:
for (int i = 0; i < 50; i++)
{
sum = sum + Math.exp(-lambda * T) * Math.pow(lambda * T , i) / (i*=1) * X;
}
But It didnt work. Any idea how to write Application.Fact(i) function in Java?

You need to implement factorial(i) yourself in Java.
Just a hint: make sure it does not overflow.
If needed use the BigInteger class (from the Java libraries).

Related

Solve harmonic-factorial sequence with java recursion

I'm trying to understand reqursion, but I have found one task, I couldn't solve for few days already.
X = 1/1 + 1/(1*2) + 1/(1*2*3) + 1/(1*2*3*4) + 1/(1*2*3*4*5) .....
how can I solve it for 100 repeats without conditional operators?
Can it be solved without recursion?
I've tried this code, but it doesn't work correctly and it contains "If".
public static double harFac(double n) {
if (n == 1) return 1;
return (1.0 / (n * harFac(n - 1))) + harFac(n - 1);
}
I believe you could do something like this:
double result = 0;
int div = 1;
for (int i = 1; i <= 100; i++){
result += 1.0 / div; /*the division needs to take place in floating point*/
div *= i+1;
}
You'll very quickly run into trouble if you evaluate the denominator like that as it will run to a limit very quickly. When working with floating point, it's also a good idea to evaluate the smaller terms first.
Fortunately you can solve both of these problems by recasting the expression to
1 * (1 + 1/2 * ( 1 + 1/3 * (1 + 1/4 * ( ... ) ) ) )
So your final term is in the recursion is foo = 1 + 1.0/100, the penultimate term in the recursion is 1 + 1/98 * foo, and so on.
I personally wouldn't use recursion to solve this, rather use a loop in a single function.
You're along the right lines but you shouldn't be calling harFac twice. You need to instead calculate the divisor. I can't see how you would do this without an if condition, though.
public static double harFac(double n)
{
if (n == 1) return 1;
int divisor = 1;
for (int i = 2; i <= n; ++i) divisor *= i;
return (1.0 / divisor) + harFac(n - 1);
}
This doesn't work beyond around n = 30 because the divisor becomes so massive.

Recursive function to iterative function as binoms

I'm new with algorithms and wonder how this displayed function is supposed to be converted/transformed from recursive to iterative. What should I keep in mind when converting?
public int binom(int n, int k)
{
if (k == 0 || n == k) { return 1; }
return binom(n - 1, k - 1) + binom(n - 1, k);
}
Thanks in advance!
In fact, this problem is not so easy, if you just look at the recursive code and try to decrypt it.
However, it might be a helpful hint for you, that (n over k), i.e. the binomial coefficient can be written as
n! / (k! * (n - k)!)
where "!" denotes the factorial.
And it should be rather easy to compute the factorial in a Loop (i.e. iterative) for you.
If intermediate results are too big you can shorten before computation. You can shorten either term k! or the term (n-k)! (you would choose the bigger one). For example with n = 5 and k = 3 you have:
(1 * 2 * 3 * 4 * 5) / ((1 * 2 * 3) * (1 * 2)) = (4 * 5) / (1 * 2)
Spoiler-Alarm:
public static int binomial(int n, int k) {
int nMinusK = n - k;
if (n < nMinusK) {
//Switch n and nMinusK
int temp = n;
n = nMinusK;
nMinusK = temp;
}
int result = 1;
// n!/k!
for (int i = k + 1; i <= n; i++) {
result *= i;
}
//Division by (n-k)!
for (int j = 1; j <= nMinusK; j++) {
result = result / j;
}
return result;
}
You can use the multiplicative form of binomial coefficients, for example from Wikia, which can be easily implemented with faculties or loops.

Poisson Distrubtion using Normal Approximation in Java

If you are unsure of what "Poisson Distrubtion using Normal Approximation" means, follow this link and check the texts inside the yellow box.
https://onlinecourses.science.psu.edu/stat414/node/180
Here, is the simple snapshot of the math from the link.
P(Y≥9) = P(Y>8.5) = P(Z>(8.5−6.5)/√6.5) = P(Z>0.78)= 0.218
So to get the value in .218, we use Simpson's integration rule which
integrates the function(Implemented in method named "f" from code below) from "negative
infinity" to the value that equals to this >> "((8.5−6.5)/√6.5))"
R successfully gives the correct output. But in Java when i implemented the code
below copied from "http://introcs.cs.princeton.edu/java/93integration/SimpsonsRule.java.html"
I get "0.28360853976343986" which should have been ".218" Is it any how because of the negative infinity value I am using, which is "Double.MIN_VALUE"
This is the code in Java. See at the very end for my INPUTS in the main method.
* Standard normal distribution density function.
* Replace with any sufficiently smooth function.
**********************************************************************/
public static double f(double x) {
return Math.exp(- x * x / 2) / Math.sqrt(2 * Math.PI);
}
/**********************************************************************
* Integrate f from a to b using Simpson's rule.
* Increase N for more precision.
**********************************************************************/
public static double integrate(double a, double b) {
int N = 10000; // precision parameter
double h = (b - a) / (N - 1); // step size
// 1/3 terms
double sum = 1.0 / 3.0 * (f(a) + f(b));
// 4/3 terms
for (int i = 1; i < N - 1; i += 2) {
double x = a + h * i;
sum += 4.0 / 3.0 * f(x);
}
// 2/3 terms
for (int i = 2; i < N - 1; i += 2) {
double x = a + h * i;
sum += 2.0 / 3.0 * f(x);
}
return sum * h;
}
// sample client program
public static void main(String[] args) {
double z = (8.5-6.5)/Math.sqrt(6.5);
double a = Double.MIN_VALUE;
double b = z;
System.out.println(integrate(a, b));
}
Anybody has any ideas? I tried using Apache math's "PoissonDistribution" class's method "normalApproximateProbability(int x)". But the problem is this method takes an "int".
Anyone has any better ideas on how do I get the correct output or any other code. I have used another library for simpson too but I get the same output.
I need this to be done in Java.
I tried to test the code by writing another method that implements Simpson's 3/8 rule instead of your integrate function. It gave the same result as the one you obtained at first time. So i think the difference arises most probably from rounding errors.

How can I fix the undefined operator in the last expression: trial = trial / numtrials * 4?

// write static methods here
public static double [] calcDarts(double [] trial, int numtrials)throws IOException
{
double x;
double y;
for(int n = 0; n < numtrials; n++)
{
x = Math.random();
y = Math.random();
double radius = (Math.pow(x, 2) + Math.pow(y,2));
if(radius <= 1)
trial = trial / numtrials * 4;
}
}
The error says the last line of code: trial = trial / numtrials * 4; "The operator / is undefined for the argument type(s) double[], int." How can I have it produce a double value for the variable trial?
You can't use a double array to calculate with an integer. Do it like this: You have to use the double values in the array:
for(int n = 0; n < numtrials; n++)
{
x = Math.random();
y = Math.random();
double radius = (Math.pow(x, 2) + Math.pow(y,2));
if(radius <= 1)
trial[n] = trial[n] / numtrials * 4;
}
But I think it is not good to calculate directly with the parameter. Create inside a Array to put the result and return it or something like that.
trial is an array of doubles, the operators / and *are obviously not defined for the use with an array. What you problably want to do is multiplying a single number form the array like this:
trial[n] = trial[n] / numtrials * 4;

java code to compute some multiple of a number?

I am using Math.PI in my example, so it is a double. It is a simple code but there is a bit I am not sure how to do:
I want the code to calculate the fundamental period X of a sin or cos function with a multiplier value a given by the user. The n value is initialized at n=1 and is an integer value.
If the result of (2 * pi * n)/a = X is lower than pi then n should increment, and it should keep going until that number is a multiple of pi, then print the result.
Just to clarify: a is a multiplier of x which goes in the function sin or cos like this:
cos(ax)
sin(ax)
The bit I am having the trouble with is working out whether the number is a multiple of pi (provided it's already greater than pi, that is).
This is about as far as I got and it's incomplete.
public void printSinusoidalPeriod(double multiplier /* this would be `a` */){
double pi=Math.PI;
double p = (2 * pi * (double) n) / multiplier;
while(p<pi){
if(n%pi==0){
n=n+1;
System.out.println(n);
p = (2 * pi * (double) n) / multiplier;
}
}
p= (double)Math.round(p * 100) / 100;
System.out.println("period of function is = " + p + " and n = " + n);
}
It seems like it's not going into the if statement and getting caught in the while loop
If I understand your problem correctly, I had to solve a similar problem to this before using php. Not sure what the correct syntax is for javascript but maybe you should keep a counter that continues until (x/pi) is an integer which would indicate it is a multiple of pi..
I know this isn't the correct code but something like:
while (!isint(x/pi)) {
x++;
}
if (isint(x/pi)) {
//CODE TO EXECUTE
}
If I understand you correctly
while((2 * pi * n)/a)<pi)
{
if(!(n%pi==0))
{
n++;
}
}
multiple of y is the part you need to figure out yourself. but this should help you with the logic, If I have understood u correctly.
You appear to be calculating when
(2 * pi * n)/a = m * pi where m is some integer multiple.
so
2 * pi * n = m * pi * a
2 * n = m * a
n = m * a / 2
You other constraint is
(2 * pi * n)/a < pi
so
2 * pi * n < pi * a
2 * n < a
n < a / 2;
For both equations to be true, m must be an integer less than 1, but since you are starting at 1 for n it will never be true.
Ok here's how I did it in the end, with the help of the suggestions here.
public void printSinusoidalPeriod(double a){
double pi=Math.PI;
double p=m*pi;
while(n<a/2){
if((double)Math.round((n*pi)%pi)!=0.01){
n=n+1;
m = (int) Math.round(((2 * (double) n) / a));
p= (double)Math.round(m * pi * 100) / 100;
p=p*n;
}
}
System.out.println("period of function is = " + p + " and n = " + n);
System.out.println("Check: p/n = " + p/n);
}
Please let me know if you can spot any problems with the logic. I have not gone through many possibities yet, but the ones I did, looked okay to me.

Categories

Resources