run an entire program a certain number of times via input - java

So my current code effectively runs the "random walk" problem and then uses the pythagorean theorem to figure out actual distance in units walked but now I need to modify my program so that I can do a certain number of trials of said walk and then calculate the mean square distance. Not really looking for just an answer, I really also need an explanation so that I may be able to learn and recreate, I think I just need another while loop but I'm not sure where to put it.
import javax.swing.JOptionPane;
String a = JOptionPane.showInputDialog("Enter # of footsteps.");
int z = Integer.valueOf(a);
int x= 0; // starting x position
int y= 0; // starting y position
double r;
int counterZ = 0;
if (z < counterZ ){
System.out.println("Error");
}
while ( z > counterZ){
r=Math.random();
if (r<0.25){
x=x+1;
}
else if(r > .25 && r<0.50){
x=x-1;
}
else if(r > .5 && r<0.75){
y=y+1;
}
else{
y=y-1;
}
counterZ = counterZ + 1;
System.out.println("(" + x + "," + y + ")");
}
System.out.println("distance = " + round(sqrt((x*x)+(y*y))));

Correct me if i am wrong, My understanding is that you want to run the walk cycle a certain number of times and calculate the average distance walked on the sum of the distance of the cycles. If that is the case, then all you have to do is this,
int noc = Integer.valueOf(JOptionPane.showInputDialog("Enter # of cycles: "));
String a = JOptionPane.showInputDialog("Enter # of footsteps.");
int z = Integer.valueOf(a);
int sum = 0;
double avg = 0.0;
for(int i=0;i<noc;i++) {
sum+= randomWalk(z);
}
avg=(double)sum/noc;
System.out.println("the average distance walked in "+ noc + "cycles is "+avg);
the randomWalk() method should be like the following if you are calling it from the main method without creating an object for the class randomWalk() is residing in.
public static int randomWalk(int z) {
//place your code here, starting from the `int x=0;`
//at last instead of printing the distance walked use the following code
return (int) Math.round(Math.sqrt((x*x)+(y*y)));
}
you have also missed to call the methods round() and sqrt() using there class Math. I have correct them for you as Math.round() and Math.sqrt(). without the class name you will get a compiler error like Symbol not found. i also assume you have imported the java.lang.Math class into your program.

I'd suggest starting by indenting the code tidily so that it is more understandable.
To address your question directly, I'd suggest modifying the program so that the substance of the progam is embedded in a method (you might call it randomWalk(), perhaps) and the main() method just calls randomWalk() and does the I/O. Having done that, it would be very easy to modify the main() method to call randomWalk() many times from within a while loop.

Related

How to write a java program that computes the value of e^x

I'm trying to figure out how to answer this question for my Java class, using only while loops:
Write an application that computes the value of mathematical constant e^x by using the following formula. Allow the user to enter the number of terms to calculate. e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...
I can't figure out how I would do this without also asking the user for a value for x? Below is the code that I created for calculating x with the number of terms and just the number 1 for the exponent of each fraction. Any help is appreciated
import java.util.Scanner;
public class FactorialB {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int counter = 0;
float answer = 0;
System.out.print("Enter number of terms: ");
int n = scanner.nextInt();
while (counter < n) {
double factorial = 1;
int factCounter = counter;
while (factCounter > 1) {
factorial = factCounter * factorial;
factCounter--;
}
answer += 1 / factorial;
counter++;
}
System.out.printf("e = %f%n", answer);
}
}
Firstly the question you seem to be asking:
There is no way to make a program that will give e for a specific number unless you ask the user for that number.
However it might be that they just want you to make a method that provides the solution (if it were called) independently of user input. (because the code to get user input isn't very interesting, what is interesting is how you reach the result).
An alternative way to provide x and n are for instance passing them as commandline arguments. (args[] in your main would be a way to provide them)
I would create a separate method that receives x and n that covers the main calculation:
e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...
And separate methods that cover 'calculating a single term (x^1/1!), (x^2/2!), etc' and 'factorialize(n)'
public void calculatePartialE_term(int x, int n) {
if (n == 0) {
return 1; // this will allow you to use a while loop, covers the n = 0 case
} else {
// removed the implementation, but basically do
// x^n/n! here for whatever value of n this term is calculating.
}
}
public int calcualteNFactorial(int n) {
// assert n >= 1
// use a while loop to calculate n factorial
}
the benefit of doing this in a separate methods is that you can prove / verify the working of calculatePartialE_term or calcualteNFactorial independently of one another.
now you can simply write a while loop based on x and n to do something like
public int calculateE_to_x(int x, int n) {
int current = 0;
int sum = 0;
while (current <= n) {
sum += calculatePartialE_term(x, current);
}
}
I wouldn't expect your teacher to expect you to show code that handles user input but even if that is the case it will be easier for them to verify your work if the actual work (of calculating) is done in a separate method.

Rolling two dice and obtaining the average of count

I'm writing a java program that simulates rolling two dices and incrementing a counter whenever both dices do not have the same face. After a number of rolls, i want to print out the average of the count.
int i = 0;
int count = 0;
double average = 0;
int j = 0;
while (i<1000) {
int dice1 = getRandom(1,6);
int dice2 = getRandom(1,6);
if (dice1 != dice2) {
count++;
}
while (j!= 1000) {
average = (count/j);
j++;
}
i++;
}
System.out.println(average)
The program doesn't give me the average as I'm quite sure the nested while loop is written wrongly?
the getRandom() function returns a random value between 1 to 6 since a dice can have 6 values.
private static int getRandom(int n1, int n2){
int retVal = 0;
retVal = n1 + (int) Math.floor(Math.random() * (n2 - n1 + 1));
return retVal;
}
I'm a beginner at java, would appreciate some help on this.
Your logic should be:
Make some number of dice rolls, and record the number of non equal rolls, and the total number of rolls
Then take the average outside of the loop
Something like this:
static final int NUM_ROLLS = 1000;
for (int i=0; i < NUM_ROLLS; ++i) {
int dice1 = getRandom(1,6);
int dice2 = getRandom(1,6);
if (dice1 != dice2) {
count++;
}
}
double average = 1.0*count / NUM_ROLLS;
System.out.println(average)
Note carefully that in the division multiplies by 1.0, to force double precision division.
The biggest problem I saw in your code is that you were taking the average inside the loop, which doesn't make sense, because your tally of non equal rolls has not yet finished.
Name your variables better.
Instead of i, call it rolls
Instead of count, call it nonmatching.
Then you'll see that you have this third, unnecessary variable called j which is really not providing anything to the solution (except being a main part of the source of your current problem).
Naming variables in a way that they provide you value is a hard thing. Get started on it early, it will save you more time when rereading your code than any other skill.
For pointers, read up on "intentional naming" which means, "naming the variable how you intend to use it" and not the obvious "naming it the way you intended to name it" (I swear I heard a developer describe it that way to me /shudder/)
Yes, you can do the calculation once, outside of the loop, too. But you'd get the right answer if you started with the right inputs.

Calculating Pi using a while loop and recursive method (Java)

My assignment was to calculate Pi using an algorithm he gave us in class, determine correct digits, and estimate Pi to six digits using a while loop and a recursive method. But my "super smart professor" didn't tell us a bloody thing about recursive methods and when I email him, he gets angry at me for not getting it just by looking at it. This is my code so far, I left out my while loop method and recursive method because I have no idea how to do those.
public static final double REAL_PI = 3.14159;//PI is the value prof gave us on the handout
public static double Pi = 0; //Pi is the value of Pi that this program calculates
public static int m = 0;
public static void main (String [] args)
{
Algorithm(); //calls on method of calculating pi
System.out.println("Calculated pi: " + Pi); //prints out pi
countDigits(Pi); //calls on countdigits method
System.out.println("Number of digits: " + c); //has the computer print out the count because that's how many digits are the same
PiRecur(); //calls on estimate digits method
}
public static double Algorithm() //should return a double (pi)
{
for(m=1; m<=100000; m++)
{
Pi += 4*(Math.pow(-1, m-1)/((2*m)-1));//Math.pow uses math package to calculate a power to use the algorithm
}
return Pi;
}
public static int countDigits (double Pi)
{
int a = (int) Pi; //the int cast makes Pi and REAL_PI into integers so the program can compare each digit separately
int b = (int) REAL_PI;
int c = 0;
int count = 0;
while(a == b)//if m less then or equal to 100,000 then while loop runs
{
count ++;
a = (int) (Pi*(Math.pow(10,count))); //if a=b then the computer will multiply Pi and REAL_PI by 10
b = (int) (REAL_PI*(Math.pow(10,count)));
/*when you input a and b
* while loop compares them
* if a = b then loop continues until a doesn't equal b and loop ends
*/
}
c = count; //gives c the value of the count so it can be used outside the method
return count;
}
}
I'm not sure how a solution that uses a while loop and recursion would loop like, since I can't read your professor's mind, but I can think of two different solutions that use one or the other.
Using while loop :
You don't run your algorithm an arbitrary number of iterations (100000 in your example) and hope that you got close enough to the expected result. You use a while loop, and on each iteration you check if your current calculation of Pi is close enough to your target.
public static double Algorithm()
{
int m = 1;
double Pi = 0.0;
while (countDigits(Pi) < 6) {
Pi += 4*(Math.pow(-1, m-1)/((2*m)-1)); // I'm assuming this formula works
m++;
}
return Pi;
}
Using recursion :
The same solution can be translated into a recursion. This time, you supply an initial index m (1) and an initial value of Pi (0) to Algorithm. The method adds the m'th term to Pi. If the new value of Pi is not good enough (determined by countDigits), you make a recursive call that would add the m+1th term to Pi and check again if the new value is good enough. The recursion would stop when the value of Pi is 6 digits accurate.
public static double Algorithm(int m,double Pi)
{
Pi += 4*(Math.pow(-1, m-1)/((2*m)-1));
if (countDigits(Pi) < 6)
Pi += Algorithm(m+1,Pi);
return Pi;
}
You call the method with :
Algorithm (1,0.0);

Calculating Least Common Multiple (how do I know when there isn't one?)

The code below was my first attempt at a LCM (lowest common multiple) calculator with a user interface (UI code not shown) written months ago. I know there are simpler ways to write this, but I'd like help understanding why sometimes THIS specific code is not finding a common multiple (with most number sets it works fine).
When a user inputs almost any number set, the app spits out the correct LCM. But when the number set 1,234 / 2,345 / 5,432 / 4,321 is used, the app initially was stopping when x hit 536,870,912. This was because the result of x * mult was a number that couldn't be held by the int primitive. After changing x to a double and casting result = (int) (mult * x), the code continues to function as expected but seems to increment x indefinitely.
public static void compare(){
result = 0;
int mult = 0;
double x = 1;
int[] nums = UserInterface.getNums();
// finds highest number in user-input set
for(int i = 0; i < nums.length; i ++){
if (nums[i] > mult) mult = nums[i];
}
// finds lowest common multiple
for(int i = 0; i < nums.length;){
if((mult * x) % nums[i] == 0){
result = (int) (mult * x);
i++;
}
else{
result = 0;
x++;
i = 0;
}
}
}
We know the LCM of your test set must be less than or equal to 67,920,681,416,560.
In java the int datatype has a max value of 2^31-1 = 2,147,483,647 so you are obviously going to get an overflow. You can change your code to use long throughout this has a max value of 2^64-1=18,446,744,073,709,551,615 so it should be sufficient for your calculation. If you need bigger values then look at the BigInteger class.
In javascript things are more complicated. All numbers are floating point so you loose accuracy. This probably mean the condition
if((mult * x) % nums[i] == 0)
is never satisfied so your loop never quits.
Your algorithm is very basic, there are much better algorithms out there, elclanrs has one above and see https://en.wikipedia.org/wiki/Least_common_multiple for some hints.
Also you should change the title of the question. As it stands it make no sense as any set of numbers must have a LCM.

Calculating Pi to a specific number of terms in Java?

I've been given the following assignment and my code isn't working. The question is:
Using a while or a do-while loop, write a program to compute PI using the following equation: PI = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ... Allow the user to specify the number of terms (5 terms are shown) to use in the computation. Each time around the loop only one extra term should be added to the estimate for PI.
This is the code I have so far:
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.lang.Math;
public class LabFriday25 {
public static void main(String[] args) {
String termInput = JOptionPane.showInputDialog(null, "How many terms of
PI would you like?");
Scanner termScan = new Scanner (termInput);
double termNum = termScan.nextDouble();
double pi = 3;
int count = 0;
double firstMul = 2;
double secMul = 3;
double thirdMul = 4;
double totalMul = 0;
while (count<= termNum)
{
if (termNum==1)
{
pi = 3.0;
}
else if (count%2==0)
{
totalMul= (4/(firstMul*secMul*thirdMul));
}
else
{
totalMul = -(4/((firstMul+2)*(secMul+2)*(thirdMul+2)));
}
pi = pi + (totalMul);
firstMul = firstMul + 2;
secMul = secMul + 2;
thirdMul = thirdMul + 2;
//totalMul = (-1)*totalMul;
count++;
}
JOptionPane.showMessageDialog(null, "The value of pi in " + termNum + " terms is : " + pi);
}
}
I can't figure out why the code won't return the right value for 3 or more terms of Pi, it keeps giving the same value every time.
EDIT: I removed the semi-colon from the end of the while statement and now the code is returning the value 3.0 for any number of terms inputted by the user. Where am I going wrong?
EDIT2: Removed condition from while loop. Answers are closer to being correct, but still not accurate enough. How can I correct this to give me the right answer?
The semi-colon at the end from the while statement is evaluated independently causing the body of the loop to execute unconditionally so the result is always the same
while (count > 0 && count <= termNum);
^
In addition the loop is terminating after the first iteration. Remove the first expression from the loop, i.e.
while (count <= termNum) {

Categories