Updating my variables in a for loop? - java

I'm trying to update my variable startPreyPopulationSize and startPredatorPopulation size everytime it iterates but I'm not sure how to go about that since the bottom for loop affects the top one right?
//Equation to find out prey population size.
for(double rate = 0; rate <= numberOfPeriods; rate++) {
double partOne = startPreyPopulationSize / rate * (1 + RATE_A_BIRTH - RATE_B_PREDATION * (startPredatorPopulationSize / rate));
double updatedPreyPopulation = startPreyPopulationSize / (rate + 1);
updatedPreyPopulation = partOne;
System.out.printf("Period %5.0f: Prey Population %.2f; \n", rate, updatedPreyPopulation);
}
//Equation to find out predator population size.
for(double rate2 = 0; rate2 <= numberOfPeriods; rate2++) {
double partTwoEquation = startPredatorPopulationSize / rate2 * (1 - RATE_C_DEATHS + RATE_D_INCREASE * (startPreyPopulationSize / rate2));
double updatedPredatorPopulation = startPredatorPopulationSize / (rate2 + 1);
updatedPredatorPopulation = partTwoEquation;
System.out.printf("Period %5.0f: Predator Population %.2f; \n", rate2, updatedPredatorPopulation);
}
UPDATED CODE I'm basing my formula off of this if it helps http://i.imgur.com/rUQ774q.jpg I know my formula is off somehow.
//Equation to find out prey population size.
for(double rate = 0; rate < numberOfPeriods; rate++) {
partOne = startPreyPopulationSize / rate * (1 + RATE_A_BIRTH - RATE_B_PREDATION * (startPredatorPopulationSize / rate));
currentPreyPopulationSize = startPreyPopulationSize / (rate + 1);
currentPreyPopulationSize = partOne;
System.out.printf("Period %5.0f: Prey Population %.2f; \n", rate, currentPreyPopulationSize);
partTwoEquation = startPredatorPopulationSize / rate * (1 - RATE_C_DEATHS + RATE_D_INCREASE * (startPreyPopulationSize / rate));
currentPredatorPopulationSize = startPredatorPopulationSize / (rate + 1);
currentPredatorPopulationSize = partTwoEquation;
System.out.printf("Period %5.0f: Predator Population %.2f; \n", rate, currentPredatorPopulationSize);
startPreyPopulationSize = currentPreyPopulationSize;
startPredatorPopulationSize = currentPredatorPopulationSize;
}

Well your code for equations you provided is wrong.
1) In equation you have no division by rate, so it should look like
double currentPreyPopulationSize = startPreyPopulationSize * (1 + RATE_A_BIRTH - RATE_B_PREDATION * (startPredatorPopulationSize));
2) Also this division causing the -Infinity, because rate is 0 for the first iteration.

Related

My code does exactly what it has to do, but i have no idea why

is supposed to calculate the coordinates of a projectile launched with respect to time (steps of 100ms), with a linear equation, and it outputs linear numbers, but if i plot this equation with CalcMe.com (math tool) it makes a parabolic plot
InVel = Double.parseDouble(jTextField1.getText());
g = Double.parseDouble(jTextField8.getText());
y = 1;
while(y >= -1) {
t += 100;
x = InVel * TimeUnit.MILLISECONDS.toSeconds(t) * Math.cos(45);
y = InVel * TimeUnit.MILLISECONDS.toSeconds(t) * Math.sin(45) - (1 / 2) * g * Math.pow(TimeUnit.MILLISECONDS.toSeconds(t), 2);
//System.out.print(Double.toString(x));
//System.out.printf(" ");
System.out.print(Double.toString(y));
System.out.printf("%n");
}
jTextField6.setText(Double.toString(x));
the code is in java
g is constant (9.8)
and invel is given by user so its constant too
g is the gravity and invel the initial velocity of the projectile
the equation is:x=invel*time*cos(45) and y=invel*time*sin(45)-(1/2)*g*t^2
anyone can help me?
Your milisecond to second value conversion method TimeUnit.MILLISECONDS.toSeconds(t) is the main fact. Its returning long value which one you are wanted double. Please take a look on below code. Probably its your answer. Just replace hard-coded value with your jTextField
public static void main(String[] args) {
double InVel = Double.parseDouble("10.555");
double g = Double.parseDouble("9.8");
double y = 1;
double x=0;
double t=0;
while(y >= -1) {
t += 100;
double timeInSeconds = (t / (double)1000) % (double)60;
x = InVel * timeInSeconds * Math.cos(45);
y = InVel * timeInSeconds * Math.sin(45) - ((double) 1 / (double) 2) * g * Math.pow(timeInSeconds, 2);
//System.out.print(Double.toString(x));
//System.out.printf(" ");
System.out.println("X = " + x + " Y = " + Double.toString(y));
System.out.printf("%n");
}
}

my math is broken on TextView

To be honest I've just started with programming but for the life of me I can't figure out where I'm wrong.
the math is:
10$ / 2 hours
tips per hour = 5 (i get 0.2)
waiter 1 pay = 10 (i get 0.4?)
screenshot
The Calculation in MainActivity:
double resultTotalHours = cWaiter1Hours + cWaiter2Hours + cWaiter3Hours + cWaiter4Hours;
double calcTipsPerHour = resultTotalHours / totalTips;
double resultBarsCut = (totalTips * (cBarCutInput / 100));
double resultTaxDeposit = resultTotalHours * 3;
double resultTipsPerHour = (totalTips - resultBarsCut - resultTaxDeposit) / resultTotalHours;
double resultWaiter1Pay = cWaiter1Hours * resultTipsPerHour;
double resultWaiter2Pay = cWaiter2Hours * resultTipsPerHour;
double resultWaiter3Pay = cWaiter3Hours * resultTipsPerHour;
double resultWaiter4Pay = cWaiter4Hours * resultTipsPerHour;
double resultWaiter1NoTax = cWaiter1Hours * calcTipsPerHour;
double resultWaiter2NoTax = cWaiter2Hours * calcTipsPerHour;
double resultWaiter3NoTax = cWaiter3Hours * calcTipsPerHour;
double resultWaiter4NoTax = cWaiter4Hours * calcTipsPerHour;
Casting the results to the TextViews:
if (calcTipsPerHour <= 30) {
totalHoursView.setText(Double.toString(resultTotalHours));
tipsPerHourView.setText(Double.toString(calcTipsPerHour));
barsCutView.setText(Double.toString(0));
taxDepositView.setText(Double.toString(0));
waiter1Pay.setText(Double.toString(resultWaiter1NoTax));
waiter2Pay.setText(Double.toString(resultWaiter2NoTax));
waiter3Pay.setText(Double.toString(resultWaiter3NoTax));
waiter4Pay.setText(Double.toString(resultWaiter4NoTax));
} else {
totalHoursView.setText(Double.toString(resultTotalHours));
tipsPerHourView.setText(Double.toString(resultTipsPerHour));
barsCutView.setText(Double.toString(resultBarsCut));
taxDepositView.setText(Double.toString(resultTaxDeposit));
waiter1Pay.setText(Double.toString(resultWaiter1Pay));
waiter2Pay.setText(Double.toString(resultWaiter2Pay));
waiter3Pay.setText(Double.toString(resultWaiter3Pay));
waiter4Pay.setText(Double.toString(resultWaiter4Pay));
}
The problem is here:
double calcTipsPerHour = resultTotalHours / totalTips;
This is currently doing 2 / 10 = 0.2.
You want to do the reciprocal:
double calcTipsPerHour = totalTips / resultTotalHours;
This should also fix your waiter's pay
You put hours in the numerator and tips in the denominator so you are getting the inverse of what you want: hours/tip
What you want is:
double calcTipsPerHour = totalTips / resultTotalHours;

Three random points on a circle

I'm trying to create a program where three random points in a circle are created and result in the creation of an inscribed triangle. However, the angles I'm getting are all screwed up
Here is my code:
public static void main(String[] args) {
double r = 40.0;
double angle1 = Math.random()* (2 * Math.PI);
double angle2 = Math.random()* (2 * Math.PI);
double angle3 = Math.random()* (2 * Math.PI);
double x_1 = r * Math.cos(angle1);
double y_1 = r * Math.sin(angle1);
double x_2 = r * Math.cos(angle2);
double y_2 = r * Math.sin(angle2);
double x_3 = r * Math.cos(angle3);
double y_3 = r * Math.sin(angle3);
System.out.println("The coordinates of the three points are:
(" + x_1 + ", " + y_1 + ")
(" + x_2 + ", " + y_2 + ")
(" + x_3 + ", " + y_3 + ")");
//Get length of each side
double distanceFrom1To2 = Math.sqrt(Math.pow(x_2 - x_1, 2) +
Math.pow(y_2 - y_1, 2));
double distanceFrom2To3 = Math.sqrt(Math.pow(x_3 - x_2, 2) +
Math.pow(y_3 - y_2, 2));
double distanceFrom3To1 = Math.sqrt(Math.pow(x_1 - x_3, 2) +
Math.pow(y_1 - y_3, 2));
//Get angles ***
double triangleAngle1 = Math.atan(distanceFrom1To2 / distanceFrom2To3);
double triangleAngle2 = Math.atan(distanceFrom2To3 / distanceFrom3To1);
double triangleAngle3 = Math.atan(distanceFrom3To1 / distanceFrom1To2);
System.out.println("The three angles are " + triangleAngle1 + " " +
triangleAngle2 + " " + triangleAngle3);
System.out.println(triangleAngle1 + triangleAngle2 + triangleAngle3);
}
I definitely know that the means of getting the angles are screwed up. Here is a sample run of my program:
The coordinates of the three points are: (5.224534224725408,
-39.65733528787168) (-29.696946087404676, 26.79722733944279)
(32.70889681040468, -23.02451018906371)
The three angles are 0.7545364726122026 1.18830825410364
0.40435068059871415
Total angle sum: 2.347195407314557
The angles all add up to much greater than Pi / 2 radians. I've considered the law of sines but you have to know at least one angle for that...
Figured it out
Here is the fixed code:
//Get length of each side
double a = Math.sqrt(Math.pow(x_2 - x_1, 2) + Math.pow(y_2 - y_1, 2)); // distance from 1 to 2
double b = Math.sqrt(Math.pow(x_3 - x_2, 2) + Math.pow(y_3 - y_2, 2)); // distance from 2 to 3
double c = Math.sqrt(Math.pow(x_1 - x_3, 2) + Math.pow(y_1 - y_3, 2)); // distance from 3 to 1
//Get angles ***
double triangleAngle1 = Math.acos((Math.pow(a, 2) + Math.pow(b, 2) - Math.pow(c, 2)) / (2 * a * b));
double triangleAngle2 = Math.acos((Math.pow(b, 2) + Math.pow(c, 2) - Math.pow(a, 2)) / (2 * c * b));
double triangleAngle3 = Math.acos((Math.pow(c, 2) + Math.pow(a, 2) - Math.pow(b, 2)) / (2 * a * c));
I changed it to use the law of cosines.

Math.ceil not rounding the value

double totalInches = d * 0.3937;
double feetPart = totalInches / 12;
int inchesPart = (int) Math.ceil(totalInches - (feetPart * 12));
return (feetPart) + "' " + inchesPart + "''";
I am getting a value 6.9999999 ' 0". I am returning a string, is it the reason why the decimals values in feet is not getting rounded off.
I tried without casting too. double inchesPart = Math.ceil(totalInches - (feetPart * 12));, but still i get the same result.
Surely you need:
int feetPart = (int)Math.floor(totalInches / 12);
or just:
int feetPart = (int)(totalInches / 12);
To get the two parts you can use
int totalInches = (int) (d * 0.3937);
int feetPart = totalInches / 12;
int feetInchPart = totalInches % 12;

Apache POI rate formula inconsistency with long periods

In order to emulate Excel's rate function, I'm using the Apache POI rate function I grabbed from the svn:
private double calculateRate(double nper, double pmt, double pv, double fv, double type, double guess) {
//FROM MS http://office.microsoft.com/en-us/excel-help/rate-HP005209232.aspx
int FINANCIAL_MAX_ITERATIONS = 20; //Bet accuracy with 128
double FINANCIAL_PRECISION = 0.0000001; //1.0e-8
double y, y0, y1, x0, x1 = 0, f = 0, i = 0;
double rate = guess;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = pv * (1 + nper * rate) + pmt * (1 + rate * type) * nper + fv;
}
else {
f = Math.exp(nper * Math.log(1 + rate));
y = pv * f + pmt * (1 / rate + type) * (f - 1) + fv;
}
y0 = pv + pmt * nper + fv;
y1 = pv * f + pmt * (1 / rate + type) * (f - 1) + fv;
// Find root by the Newton secant method
i = x0 = 0.0;
x1 = rate;
while ((Math.abs(y0 - y1) > FINANCIAL_PRECISION) && (i < FINANCIAL_MAX_ITERATIONS)) {
rate = (y1 * x0 - y0 * x1) / (y1 - y0);
x0 = x1;
x1 = rate;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = pv * (1 + nper * rate) + pmt * (1 + rate * type) * nper + fv;
}
else {
f = Math.exp(nper * Math.log(1 + rate));
y = pv * f + pmt * (1 / rate + type) * (f - 1) + fv;
}
y0 = y1;
y1 = y;
++i;
}
return rate;
}
For calculateRate(120, 28.1, -2400, 0, 0, 0.1)), the output is the same as Excel: 0.599
But if I try the same calculation, this time with the values:
calculateRate(360, 15.9, -2400, 0, 0, 0.1))
In Excel I get 0.580, and the program returns -1.1500428517726355. Any hints?
There are a bunch of things that are wrong with this code that you have pasted in your question.
It assumes that a rate is always found (not true) and makes no provision for instances when a rate is not found.
Some of the statements will throw an error which could have been avoided by using a more appropriate programming statement. For instance, take the following statement from your code:
f = Math.exp(nper * Math.log(1 + rate));
This will throw an error when attempting to find Log of a negative or zero value. It could have been rewritten as
f = Math.pow(1 + rate, nper);
The comment in iterative calculations states that it is programming the secant method, yet the iterative calculations are checked for convergence of the wrong variable. It is testing for convergence of a future value when it should be testing for convergence of the interest rate.
I copy pasted your code in Notepad and removed the variable declaration of Java and replaced these with JavaScript variable declarations to test the code with your sample data. And just as I said, the code stops at the second iteration since the difference of future values goes out of error bound and since there is no test in place to see whether a rate is found, the code returns the interest rate as is and one which is wrong.
I am not sure why this code works in instances where it does report a correct rate as is the case with first data set. I would suggest re-coding of the function in a correct manner.
public double rate(double nper, double pmt, double pv)
{
//System.out.println("function rate : " + nper + " " + pmt + " pv " + pv);
double error = 0.0000001;
double high = 1.00;
double low = 0.00;
double rate = (2.0 * (nper * pmt - pv)) / (pv * nper);
while(true) {
// Check for error margin
double calc = Math.pow(1 + rate, nper);
calc = (rate * calc) / (calc - 1.0);
calc -= pmt / pv;
if (calc > error) {
// Guess is too high, lower the guess
high = rate;
rate = (high + low) / 2;
}
else if (calc < -error) {
// Guess is too low, higher the guess.
low = rate;
rate = (high + low) / 2;
}
else {
// Acceptable guess
break;
}
}
//System.out.println("Rate : " + rate);
return rate;
}
Example: =RATE(60, 2112500, 65000000) returns 0.025198; the same with Excel (correct).

Categories