JAVA Looping a formula - java

To start, I'm a relatively new programmer as it pertains to JAVA. I've searched for many things but it's possible I'm not search for the right thing. I'm basically trying to list from the first "year" to the 10th "year" a starting amount, multiplied by the percentage, and added to the starting amount. Then, I want to take that new amount and do the same thing over and over again until it gets to 10. Or, even a specified total ex:2000.
public static void main(String[] args)
{
double startAmount = 1000;
double ratePercentage = 0.05;
double newAmount;
for (int i = 0; i <= 10; i++){
newAmount = startAmount + (startAmount * ratePercentage);
System.out.println(i + " " + newAmount);
}
}

I'm not 100% sure what you are trying to achive. But assuming you are trying to do some sort of compounding interest. This should help.
public static void main(String[] args)
{
double startAmount = 1000;
double ratePercentage = 0.05;
double newAmount;
newAmount = startAmount;
for (int i = 0; i <= 10; i++){
newAmount = newAmount + (newAmount * ratePercentage);
System.out.println(i + " " + newAmount);
}
}

Try this
public static void main(String[] args)
{
double startAmount = 1000;
double ratePercentage = 0.05;
double newAmount;
for (int i = 0; i < 10; i++){
newAmount = startAmount + (startAmount * ratePercentage);
System.out.println(i + " " + newAmount);
startAmount=newAmount;
}
}

Related

How can I summarize the probability results, that I got with a loop? (Java)

I'm wondering if is there a way to summarize the results of probability that I got through a loop? So I can know how many successful hits there were, given x number of attempts. Right now I just get a stream of 1 or 0 statements (1 for a successful hit, 0 for fail), not very practical. It looks like this:
public class doGry {
public static void main(String[] args ) {
for (int i = 0; i < 50; i++) {
// chance to hit (h) = 35% + (ma - md)
// 8% < h < 90%
double ma = 20;
double md = 10;
double probability;
System.out.println("probability of success " + (probability = 35 + (ma - md)));
double probab2 = probability / 100;
double r = Math.random();
int roll;
if (r <= probab2) roll = 1;
else roll = 0;
System.out.println(roll);
}
}
}
There are few variables that can be initialized outside of for-loop since you are not modifying its value, so no need it initialize it again and again.
Using a variable count, for keeping track of successful hits. For each successful hit, increment its value by 1.
public class doGry {
public static void main(String[] args ) {
double ma = 20;
double md = 10;
double probability = 35 + (ma - md);
double probab2 = probability / 100;
int count = 0;
for (int i = 0; i < 50; i++) {
System.out.println("probability of success " + probability);
double r = Math.random();
if (r <= probab2)
{
System.out.println("1");
count++;
}
else
System.out.println("0");
}
System.out.println("Succesful hits " + count);
}
}
All you have to do is add in a variable to keep track of how many successful rolls occurred, and then divide that by the total number of rolls using a double like so
public class doGry
{
public static void main(String[] args )
{
int total = 0;
for (int i = 0; i < 50; i++)
{
// chance to hit (h) = 35% + (ma - md)
// 8% < h < 90%
double ma = 20.0;
double md = 10.0;
double probability;
System.out.println("probability of success " + (probability = 35 + (ma - md)));
double probab2 = probability / 100;
double r = Math.random();
int roll;
if (r <= probab2) {roll = 1; total++;}
else roll = 0;
System.out.println(roll);
}
System.out.println("total: " + total/50.0);
}
}
Notice in the final System.out.println statement, the total is being divided by 50.0 (and not 50) as the .0 indicates you want a double division and not integer division, the latter of which throws away any remainder decimal values.

BigInteger Java How To Recreate A Formula

I tried to recreate this formula i am sure it's correct but the problem it gives me infinity and i need your help to transform it to BigInteger please help if possible
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
double X = Input.nextDouble();
double Y = Input.nextDouble();
double Ans = 0;
for (int I = 1; I <= 20; I++) {
for (int J = 1; J <= 20; J++) {
Ans += Math.log10(1 + Math.exp(Math.pow(-1, I + J) * (((Math.pow(I, 2) * X)) + (Math.pow(J, 2)) * Y)));
}
}
System.out.println(Ans);
}
}

Cannot figure out why i'm getting a null value in calculation

So essentially this is a simple loop that should add up for 10 seconds the distance fallen for an object. When I was debugging it I saw it passed and the variables with correct values but when I entered a println statement right after the calculation in my fallingDistance method, the variable "distance" had a value of zero which I do not see how is possible. What am I missing here?
import java.lang.Math;
import javax.swing.JOptionPane;
public class FallingDistance {
public static void main(String[] args) {
double distance =0;
int count = 0;
double distanceCalc = 0;
int varTime = 0;
while (varTime < 10) {
varTime += 1;
System.out.println(varTime);
fallingDistance(varTime);
distanceCalc += distance;
JOptionPane.showMessageDialog(null, "The distance travelled is " + distanceCalc + " meters.");
}
}
public static double fallingDistance(int varTime) {
double gravity = 9.8;
double distance = Math.pow(((1 / 2) * gravity * varTime), 2);
System.out.println(gravity);
return distance;
}
}
You must assign value to the distance before using it in main!
public class FallingDistance {
public static void main(String[] args) {
double distance =0;
int count = 0;
double distanceCalc = 0;
int varTime = 0;
while (varTime < 10) {
varTime += 1;
System.out.println(varTime);
distance = fallingDistance(varTime);
distanceCalc += distance;
JOptionPane.showMessageDialog(null, "The distance travelled is " + distanceCalc + " meters.");
}
}
public static double fallingDistance(int varTime) {
double gravity = 9.8;
double distance = Math.pow(((double)(1 / 2) * gravity * varTime), 2);
System.out.println(gravity);
return distance;
}
Please assign the value returned from fallingDistance(varTime) method to distance.
Your while loop should be rewritten as:
while (varTime < 10) {
varTime += 1;
System.out.println(varTime);
distance = fallingDistance(varTime);
distanceCalc += distance;
JOptionPane.showMessageDialog(null, "The distance travelled is " + distanceCalc + " meters.");
}
Also, your 1/2 will always be evaluated to 0 (because its evaluated as integer). The fallingDistance() method should be rewritten as:
public static double fallingDistance(int varTime) {
double gravity = 9.8;
double distance = Math.pow((0.5 * gravity * varTime), 2);
System.out.println(gravity);
return distance;
}

What is wrong with my pi calculator?

I'm using Wallis' method to calculate pi, and I think I did it right. At least I thought I did anyway. I think the problem (output is 0)has to do with rounding and remainders, though I can't be sure. Here's the code:
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 2;
int b = 3;
int c = 1;
int pi = 0;
double acc = 0.0;
int n = scan.nextInt();
scan.close();
for (int i = 0; i <= n; i++) {
pi = (2 / 3) * c;
if (a > b) {
b += 2;
} else {
a += 2;
}
c = a / b;
}
pi *= 4;
System.out.println("The approximation of pi is " + pi + ".");
acc = Math.PI - pi;
System.out.println("It is " + acc + " off.");
}
}
Since posting this I've made some changes to the code, though it's still not quite functional. I get 2.666..., so there's something else at work here as well.
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double a = 2.0;
double b = 3.0;
double c = 1.0;
double pi = 0;
double acc = 0.0;
int n = scan.nextInt();
scan.close();
for (int i = 0; i <= n; i++) {
pi = (2.0 / 3.0) * c;
if (a > b) {
b += 2;
} else {
a += 2;
}
c = a / b;
}
pi *= 4;
System.out.println("The approximation of pi is " + pi + ".");
acc = Math.PI - pi;
System.out.println("It is " + acc + " off.");
}
}
int a=2;
int b=3;
double pi=2;
for(int i=0;i<=n;i++){
pi *= (double)a/(double)b;
if(a>b){
b+=2;
} else {
a+=2;
}
}
pi*=2;
Using n = 4000 yields 3.141200
Here's the whole program, fixed:
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.close();
double pi = 2;
int a = 2;
int b = 3;
for (int i = 0; i <= n; i++){
pi *= (double) a / (double) b;
if (a > b) {
b += 2;
} else {
a += 2;
}
}
pi *= 2;
double acc = Math.PI - pi;
System.out.println("The approximation of pi is " + pi + ".");
System.out.println("It is " + acc + " off.");
}
}
Since your varibles are ints, all your divisions are integer divisions, omitting the fraction (and preserving only the whole part of the result). For accurate results, you should define your variables as doubles:
double a=2;
double b=3;
double c=1;
double pi=0;

Passing array through average method, resulting in low percent

For some reason the average is being populated wrong when I pass the array to the method I get a really low percent. It almost seems like since the Array shotsMade is only recording integers for made shots and not misses it is not calculating off the right base.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myGameCounter = 1;
int shotCount = 0;
int shotCount1 = 0;
int [] shotsMade = new int [5];
int sum = 0;
System.out.print("Enter Player's Free Throw Percentage: ");
Scanner input = new Scanner(System.in);
int percent = input.nextInt();
//Game #1
System.out.println("Game " + myGameCounter + ":");
Random r = new Random();
myGameCounter++;
shotCount = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount + " out of 10");
shotsMade[0]= shotCount;
//Game #2
System.out.println("");
System.out.println("Game" + myGameCounter + ":");
myGameCounter++;
shotCount1 = 0;
for (int i = 0; i < 10; ++i){
boolean in = tryFreeThrow(percent);
if (in) {
shotCount1++;
System.out.print("In" + " ");
}
else {
System.out.print("Out" + " ");
}
}
System.out.println("");
System.out.println("Free throws made: " + shotCount1 + " out of 10");
shotsMade[1]= shotCount1;
System.out.println("");
System.out.println("Summary:");
System.out.println("Best game: " + max(shotsMade));
System.out.println("Total Free Throws Made: " + sum(shotsMade) + " " + "out of 20");
System.out.println("Average Free Throw Percentage: " + average(shotsMade) +"%");
}//main
public static boolean tryFreeThrow(int percent) {
Random r = new Random();
int number = r.nextInt(100);
if (number > percent){
return false;
}
return true;
}
public static float average(int nums[]) {
int total = 0;
for (int i=0; i<nums.length; i++) {
total = total + nums[i];
}
float f = (total / nums.length);
return (float)total /(float)nums.length;
}
public static int sum(int nums[]) {
int sum = 0;
for (int i=0; i<nums.length; ++i) {
sum += nums[i];
}
return (int)sum;
}
public static int max(int nums[]) {
int max=nums[0];
for (int i=1; i<nums.length; i++) {
if (nums[i] > max)
max = nums[i];
}
return max;
}
}//class
You are calculating the avarage of 5 numbers but you only set 2. So if all shots hit your array will look like this: 10, 10, 0, 0, 0 and the avarage will be 4.
Old issue, you are using integer arithmetic total / nums.length with returns you an int value. You later assign it to a float, but the value already has been truncated.
Just change one of the values to float before the division, v.g. ((float) total) / num
Among others, your expression
float f = (total / nums.length);
will yield an inaccurate result.
Both total and nums.length are integers, and any operation between integers always results in an integer.
Example: if total=10 and nums.length=3, you'd expect the result to be 3.333... but actually the result is just 3. Only after that do you cast it to a float, resulting in 3.0.
To get the required result, you need to cast both integers to floats before dividing:
float f = (float) total / (float) nums.length;

Categories