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) {
Related
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.
I have been assigned to write a java program for class that counts multiples. The program takes three integers as input: low, high, x. The program then outputs the number of multiples of x between low and high exclusively.
If the input is: 1, 10, 2
the output would be: 5
My teacher has the proclivity to assign problems we haven't covered in class and I am unsure where to begin. Im not asking for the full code, just how to set up the problem
I am unsure of how to follow my logic thru the program: what I have so far is this
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int low, high, x;
int count = 0;
low = scnr.nextInt();
high = scnr.nextInt();
x = scnr.nextInt();
for(int i = low; i <= high; i++){
if(i % x == 0){
count++;
}
if (i % x != 0){
//System.out.println(count);// someone suggested to move this
}
}
System.out.println(count);
}
}
~~~~~~
If I input 1, 10, 2
My output is 01234
Moved the print of count outside of the loop... man I am tired.
FINAL EDIT: This code works, it accomplishes the goal. Thank you to #charisma and everyone else that helped me understand what was going on here. I am new to java but determined to learn more! Thanks all!!!!!
You can input numbers using scanner class similar to the following code from w3schools:
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
low, high and x can be of data type int.
To check which numbers between low and high are multiples of x, you can use a for loop. You can declare a new variable count that can be incremented using count++ every time the for loop finds a multiple. The % operator could be useful to find multiples.
You can output using System.out.println(" " + );
Edit:
% operator requires 2 operands and gives the remainder. So if i % x == 0, it means i is a multiple of x, and we do count++.
The value of i will run through low to high.
for (i = low; i <= high; i++) {
if (i % x == 0) {
count++;
}
}
Once you get to the basic implementation (as explained by Charisma), you'll notice, that it can take a lot of time if the numbers are huge: you have high - low + 1 iterations of the loop. Therefore you can start optimizing, to get a result in constant time:
the first multiple is qLow * x, where qLow is the ceiling of the rational quotient ((double) low) / x,
the last multiple is qHigh * x, where qHigh is the floor of the rational quotient ((double) high) / x,
Java provides a Math.floor() and Math.ceil(), but you can get the same result using integer division and playing with the signs:
final int qLow = -(-low / x);
final int qHigh = high / x;
Now you just have to count the number of integers between qLow and qHigh inclusive.
return qHigh - qLow + 1;
Attention: if x < 0, then you need to use qLow - qHigh, so it is safer to use:
return x > 0 ? qHigh - qLow + 1 : qLow - qHigh + 1;
The case x == 0 should be dealt with at the beginning.
put count++; after the last print statement
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);
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.
I am at the end of my homework, and a little confused on the right way to go for this algorithm. I need to find the base10 of a number:base that user gives.
Basically what my program does is take user input such as, 407:8 or 1220:5 etc.
What I am trying to output is like this.
INPUT: 407:8
OUTPUT: 407 base 8 is 263 base 10
I was thinking of this long stretched out way of doing it but I am sure there is a way easier way to go about it.
Attached is what i have so far. Thanks for looking!!
import javax.swing.JOptionPane; //gui stuff
import java.util.Scanner; // Needed for accepting input
import java.text.*; //imports methods for text handling
import java.lang.Math.*; //needed for math stuff*
public class ProjectOneAndreD //my class + program name
{
public static void main(String[] args) //my main
{
String input1; //holds user input
int val=0, rad=0, check1=0; //holds integer values user gives
and check for : handler
double answer1=0; //holds the answer!
Scanner keyboard = new Scanner(System.in);
//creates new scanner class
do //will continue to loop if no : inputted
{
System.out.println("\t****************************************************");
System.out.println("\t Loading Project 1. Enjoy! "); //title
System.out.println("\t****************************************************\n\n");
input1 = JOptionPane.showInputDialog("INPUT: ","EXAMPLE: 160:2"); //prompts user with msgbox w/ example
System.out.println("Program Running..."); //gives user a secondary notice that everything is ok..
check1=input1.indexOf(":"); //checks input1 for the :
if(check1==-1) //if no : do this stuff
{
System.out.println("I think you forgot the ':'."); //let user know they forgot
JOptionPane.showMessageDialog(null, "You forgot the ':'!!!"); //another alert to user
}
else //otherwise is they remembered :
{
String numbers [] = input1.split(":"); //splits the string at :
val = Integer.parseInt(numbers[0]); //parses [0] to int and assigns to val
rad = Integer.parseInt(numbers[1]); //parses [1] to int and assigns to rad
//answer1 = ((Math.log(val))/(Math.log(rad))); //mathematically finds first base then
//answer1 = Integer.parseInt(val, rad, 10);
JOptionPane.showMessageDialog(null, val+" base "+rad+" = BLAH base 10."); //gives user the results
System.out.println("Program Terminated..."); //alerts user of program ending
}
}while(check1==-1); //if user forgot : loop
}
}
You can use Integer.parseInt(s, radix).
answer = Integer.parseInt(numbers[0], rad);
You parse number in given radix.
It's easy, just replace your commented out logic with this:
int total = 0;
for (int i = 0; val > Math.pow(rad, i); i++) {
int digit = (val / (int) Math.pow(10, i)) % 10;
int digitValue = (int) (digit * Math.pow(rad, i));
total += digitValue;
}
and total has your answer. The logic is simple - we do some division and then modulus to pull the digit out of val, then multiply by the appropriate radix power and add to the total.
Or, if you want to make it a little more efficient and lose the exponentials:
int total = 0;
int digitalPower = 1;
int radPower = 1;
while (val > radPower) {
int digit = (val / digitalPower) % 10;
int digitValue = digit * radPower;
total += digitValue;
digitalPower *= 10;
radPower *= rad;
}
You only have implemented the user interface. Define a method taking two integers (the base and the number to convert) as argument, and returning the converted number. This is not very difficult. 407:8 means
(7 * 8^0) + (0 * 8^1) + (4 * 8^2)
You thus have to find a way to extract 7 from 407, then 0, and then 4. The modulo operator can help you here. Or you could treat 407 as a string and extract the characaters one by one and transorm each of them into an int.