this is my first interaction with this site, I have heard good things and I hope I can find the answer that I am looking for. I am learning Java and using the Eclipse IDE in a computer science class at my high school and I came across a problem that neither my teacher or I can solve. Here are the instructions.
"The German Mathematician GottfriedLeibniz developed the follow method to approximate the value of π.
π/4 = 1 - 1/3 + 1/5 - 1/7 + ...
Write a program that allows the user to specify the number if iterations used in this approximation and displays the resulting value."
Now the code.
import java.util.Scanner;
public class GottfriedLeibnizPi {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter how many iterations you want to go to: ");
int iterations = reader.nextInt();
double pi = 0;
if (iterations >= 0) {
for (int count = 0; count <= iterations - 1; count++) {
System.out.println("pi: " + pi + " count: " + count); //debug statement to show pi and count before running the code
if (count % 2 == 0) {
pi = pi + (1 / (1 + (2 * count))); // first to run. starts at pi + 1 and every other loop adds 1/(1+2n)
} else {
pi = pi - (1 / (1 + (2 * count))); // first to run. starts at pi - 1/3 and every other loop subtracts 1/(1+2n)
}
System.out.println("pi: " + pi + " count: " + count + "\n"); //debug statement to show pi and count after running the code
}
pi = pi * 4; //obtains the true value of pi
System.out.println("The value of pi after " + iterations + " iterations is " + pi);
} else {
System.out.println("Please enter a non-negative number");
}
}
}
Here is the output with the the debugging statements if I enter five at the prompt.
Enter how many iterations you want to go to: 5
pi: 0.0 count: 0
pi: 1.0 count: 0
pi: 1.0 count: 1
pi: 1.0 count: 1
pi: 1.0 count: 2
pi: 1.0 count: 2
pi: 1.0 count: 3
pi: 1.0 count: 3
pi: 1.0 count: 4
pi: 1.0 count: 4
The value of pi after 5 iterations is 4.0
My math says that answer should be 3.3396... but the math in my loop does not appear to run more than once. I have not found anything on here that is close to my problem, does anyone know what is wrong?
The problem seems to be a roundoff caused by integer division. Try replacing the relevant part of your code with this:
if(count % 2 == 0){
pi = pi + (1 / (1 + (2.0 * count))); // first to run. starts at pi + 1 and every other loop adds 1/(1+2n)
}
else{
pi = pi - (1 / (1 + (2.0 * count))); // first to run. starts at pi - 1/3 and every other loop subtracts 1/(1+2n)
}
Since "1" in the numerator is an integer, and "(1 + (2*Count))" in the denominator is also an integer, you will get integer division which truncates any remainder from the division. Since the denominator in this case is going to be greater than or equal to 1, 1/(positive integer greater than 1) will always result in 0 in integer division. By adding a decimal to one of the integers Java will treat it as a double and not perform integer division.
So actually, there is no problem with the execution of the lines. When I run the code with the above changes I get the same answer as given by your teacher.
The value of pi after 5 iterations is 3.3396825396825403
int/int gives an int type, by which you loose the fractional part of the divison ( 3/2 gives 1 ) . So you need -
pi = pi + (1.0 / (1.0 + (2 * count))); // Notice the 1.0
Similarly in the other case too.
In both the cases of:
pi = pi + (1 / (1 + (2 * count))); // (1 / (1 + (2 * count))) everything here is an int so, so you are losing . and everything after .
change it to
pi = pi + (1d / (1 + (2 * count)));
iterations=int(input('enter no of iterations'))
adding = 0
for i in range(1, iterations + 1, 2):
if i % 4 == 1:
adding += 1/i
else:
adding -= 1/i
pi = 4 * adding
Related
In my program I have a method calculateCost(), which gets the cost of a truck based on the minimum temperature of said truck.
public double calculateCost() {
int minimumTemperature = this.getTemperature();
System.out.println("Temp is: " + minimumTemperature);
double costOfTruck = 900 + 200 * (Math.pow(0.7, (minimumTemperature / 5)));
System.out.println("Cost is: " + costOfTruck);
return costOfTruck;
}
When this method is executed, the minimumTemperature correctly changes as shown in the console, however, the costOfTruck doesn't change when the minimumTemperature is changed.
If minimumTemperature < 5 then minimumTemperature / 5 will equal zero due to integer division and Math.pow(0.7, (minimumTemperature / 5) will equal 1, so try using a double numeric type
double costOfTruck = 900 + 200 * (Math.pow(0.7, (minimumTemperature / 5.0)));
I am trying to split a number of a base then separating the two numbers to get different outputs. (Keep in mind I just edited, my answer is the solution). This is left here so people that have a similar problem can find a solution. Thank you all!
So this is the idea:
If number >= 10 && of base 10
Then give me discounted price on 10 units
if number <= 0 && not base 10
Then add the discount for the number which has 10 units in it and the remainder without the discount (let's say 100% for simplicity sake of the numbers)
So to make a practical example
If I order 25 units of x (at $1 each) and 15 units (at $1 each) of y the price will be:
x 20 units = $0
x 5 units = $5 total
y 10 units = $0
y 5 units = $5 total
This is a bit tricky and this is what I got so far:
double discountedmNI = (mNI - ((mNI/100)*10)) * mNIC;
double discountedmNIP = mNI - ((mNI/100)*10);
if(mNIC >= 10 && mNIC % 10 == 0){
System.out.println("mNI " + discountedmNIP + " " + mNIC);
System.out.println(discountedmNI);
}
else if (!mNIC % 10 == 0){
System.out.println("mNI " + mNI + mNIC);
System.out.println(mNI * mNIC);
}
I don't think I am defining separate the 10 units right
Thank you all!
I hope I understood you right. I get that you want to calculate a total price that consists of two elements: the price for non-discounted items and a price for discounted items.
// The following three values are just example assumptions.
float discountInPercent = 100.0f;
float itemsOrdered = 5004.0f;
float itemPriceNormal = 5.0f;
// Here the price for one discounted item gets calculated.
// Please remember that the discount is given in percentage.
float itemPriceDiscounted = itemPriceNormal * ((100.0f - discountInPercent) / 100.0f);
// Calculate the count of items that get discounted and those that
// will get priced normally.
float itemsDiscounted = Math.floor(itemsOrdered / 10.0f);
float itemsNotDiscounted = itemsOrdered % 10;
// Finally calculate the two elements of the total price and sum it up.
float priceDiscounted = (itemsDiscounted * itemPriceDiscounted);
float priceNormal = (itemsNotDiscounted * itemPriceNormal);
float totalPrice = priceDiscounted + priceNormal;
System.out.println("Price discounted: %.2f" + priceDiscounted);
System.out.println("Price non-discounted: %.2f" + priceNormal);
System.out.println("Price total: %.2f" + totalPrice);
EUREKA!
double discountedmNIP = mNI - ((mNI/100)*10);
int mNIC2 = (mNIC % 10);
double mNIC2disc = (mNI * mNIC2);
double discountedmNI = (mNI - ((mNI/100)*10)) * (mNIC - mNIC2);
if(mNIC >= 10){
System.out.println(discountedmNIP + " " + (mNIC - mNIC2) + " " + discountedmNI );
System.out.println(mNI + " " + mNIC2 + " " + mNIC2disc);
}
else{
System.out.print(mNI + " " + mNIC);
System.out.print(mNI * mNIC);
}
double sum = (mNI + discountedmNI + discountedRh + rH);
System.out.println('\t');
System.out.println("Total order cost " + sum);
All I need to do is to take the units % 10 which will divide the left side integer or double by the right side (left side input from user)
and will give me the remainder when I do that variable subtracted to the original variable!
Again, this small step took me a whole night to figure it out, and is simple indeed. This is for a class, and if you are in that class and you are reading (even though you might have to dig a little to find what assignment is this one), I would just like to tell you this is what's fun about programming! I am not being sarcastic I really love these type of problems!
Signed:
That foreign guy;
EUREKA again!
Enjoy!
A man is keeping score of a football (soccer) game. He tracks partial results like this: 1-0, 1-1, 2-1, 2-2, 3-2. The sum of the goals in all of these partial results is 15, and the final result is 3-2, which is 5 goals. Given N which is sum of the goals of the partial results, you need to find number of goals of the final result. Here are some examples:
Input 15
Output 5
Input 6
Output 3
Input 55
Output 10
I can't use loops to solve the problem; I can only use if/else and arithmetical operations. Using just those operations, how can I find hte number of goals of the final result?
It is a summation problem. A record is created every time a goal is scored. The record is always one larger than the previous record. The total is the sum of all records.
Total = summation( number of goals scored )
So is the total is 1 then you know the number of goals is 1 as well.
If the total is three then there were two goals scored (1 and 1+1)
55 = 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 so there were 10 goals scored.
edit Calculating the actual answer is simpler than using the fractional math shown in other answers, but it requires solving a quadratic equation.
Note that the solution to ax**2 + bx + c == 0 is
x = (-b +/- SQRT( b**2 - 4*a*c) / 2*a
T = n(n+1)/2
2T = n**2 + n
n**2 + n - 2T = 0
n = (-1 +/- SQRT( 1 - 4*1*(-2T))) / (2 * 1), n > 0
n = (SQRT( 1 + 8T ) - 1) / 2
so if T = 10, n = (SQRT(81) - 1) / 2 == 4
r ="result"
s = "sum of goals"
n = "number of goals"
r s n
1-0 1 1
1-1 3 2
2-1 6 3
2-2 10 4
3-2 15 5
This tells us that s is just the sum of the first n integers, but we need n(s), not s(n).
Here's an example calculation.
Here's the code for making this happen in java:
class Example {
public static int n(int s) {
return (int) Math.round(-1.0 / 2.0 + Math.sqrt(1.0 / 4.0 + 2.0 * s));
}
public static int s(int n) {
return (n * (n + 1)) / 2;
}
public static void main(String[] args) {
for (int n = 0; n <= 10; n++) {
int s = s(n);
printResult(s);
}
}
private static void printResult(int s) {
int n = n(s);
System.out.println("If the sum of goals is " + s + ", then the number of goals is " + n);
}
}
Here's the output:
If the sum of goals is 0, then the number of goals is 0
If the sum of goals is 1, then the number of goals is 1
If the sum of goals is 3, then the number of goals is 2
If the sum of goals is 6, then the number of goals is 3
If the sum of goals is 10, then the number of goals is 4
If the sum of goals is 15, then the number of goals is 5
If the sum of goals is 21, then the number of goals is 6
If the sum of goals is 28, then the number of goals is 7
If the sum of goals is 36, then the number of goals is 8
The question is ambiguous as to whether square root is allowed, does it strictly count as an arithmetic operation?
If we assume its not allowed and we cannot use any looping we can use Newton's method to give a good approximation to the answer. Others have pointed out that we are basically trying the find the inverse of the triangular numbers T(n)=n(n+1)/2. If we are given a sum S let f(n)=n^2/2+n/2-S we want to solve f(n)=0. Newton's method is a fast iterative method, given an initial guess x0 we can find a better guess x1 using
x1 = x0 - f(x) / df(x)
where df(x)=x-1/2 is the derivative. If we do this 4 times we get a pretty good solution.
public class InverseSqrt {
static float f(float x,float S) {
return x*x/2+x/2-S;
}
static float df(float x,float S) {
return x+0.5f;
}
static float newton(float sum) {
float x = sum/2; // first initial guess
// Apply Newton's method four time
x = x - f(x,sum) / df(x,sum);
x = x - f(x,sum) / df(x,sum);
x = x - f(x,sum) / df(x,sum);
x = x - f(x,sum) / df(x,sum);
return x;
}
public static void main(String[] args) {
int i=0;
int ires=0;
do { // loop through possible number of goals
++i;
float s = i * (i+1) * 0.5f; // calculate the total
float res = newton(s);
ires = (int) (res+0.5); // round to nearest integer
System.out.print("T("+i+")="+(int)s);
System.out.println("\tres="+ires+"\t("+res+")");
} while(ires==i); // break first time it fails
}
}
This works pretty well up to an input of 351 giving an output of 26. But fails for the next input 378 giving 28 rather than 27 goal.
We can improve things a bit by using 5 steps of Newtons method working up to an input of 1176 with an output of 48. Tuning the initial guess improves things dramatically, using a starting guess of n/16 with 5 steps works upto input 42195 output 290.
A much better solution can be found using the Fast inverse squareroot. This can be implemented in Java following this answer.
static float Q_rsqrt( float x )
{
float xhalf = 0.5f*x;
int i = Float.floatToIntBits(x);
i = 0x5f3759df - (i>>1);
x = Float.intBitsToFloat(i);
x = x*(1.5f - xhalf*x*x);
return x;
}
Our Newton iteration method is then
static float newton(float sum) {
float x = Q_rsqrt(1/sum);
x = x - f(x,sum) / df(x,sum);
x = x - f(x,sum) / df(x,sum);
x = x - f(x,sum) / df(x,sum);
return x;
}
with only 3 iteration steps.
This works upto Input 1073720960 Output 46340. The next item after than gives an integer overflow in calculating the sum, so it can be said to work for all legal int values.
This might not be counted as a legal solution as it uses floatToIntBits(x) and intBitsToFloat(x) which don't really class as arithmetic operations.
It seems that sum of arithmetic progression S(n) is given, and you have to find n.
Use simple math and calculate n from equation:
S(n) = n * (n + 1) / 2
I'm attempting to calculate how much tax a user should pay, based on wage. For example, calculating 20% in the first if loop, this will be saved in generaltax:
int generalTax = 0;
int userGrossPay = 50000;
if (userGrossPay <= 10600) {generalTax += 0;}
else if (((userGrossPay >= 10600) && (userGrossPay <= 31785))) { generalTax = ((20/100) * userGrossPay); }
else if (((userGrossPay >= 31786) && (userGrossPay <= 150000))) { generalTax = ((40/100) * userGrossPay); System.out.println(generalTax);}
else if (userGrossPay > 150001) {generalTax = ((45/100) * userGrossPay); }
else{System.out.println("error");};
userGrossPay -= generalTax;
System.out.println(userGrossPay);
However generalTax pay is for some reason always stuck as 0 and is not properly updating on each iteration.
Your problem is that you are always adding 0 or assigning 0 to generalTax.
For example, (20/100) * userGrossPay is 0, since 20/100 is 0 due to int division. Change it too 0.2 * userGrossPay or 20.0/100 * userGrossPay. Similarly change all other places where you divide two integers.
This is caused by integer division.
If you mix floating data type with integer, it will give you a data conversion by promotion.
For example:
int num = 5;
System.out.println(num / 2); //Gives you 2
System.out.println(num / 2.0); //Gives you 2.5
System.out.println(num * 2); //Gives you 10
System.out.println(num * 2.0); //Gives you 10.0
System.out.println(num + 2.5); //Gives you 7.5
If all operands in the operation are integers, your output will be integer as well. This is how you got into an integer division accidentally.
((20/100) * userGrossPay);
I see that you already accepted Eran's answer and understood what went wrong, I am here to give you some additional information.
// a java program that displays the maclaurinseries math function
// sin x = x - x^3/3! + x^5/5! - x^7/7!
// sin x = (-1)^n * x^(2n+1) / (2n+1)!
import java.util.Scanner;
public class maclaurinseries
{
public static void main(String args[])
{
double x;
double counter=1;
double factorial =1;
double result=0;
Scanner input=new Scanner(System.in);
System.out.println("enter a number");
x=input.nextDouble();
while(x>=counter) {
factorial=2*factorial*counter+1;
result=result+(Math.pow(-1,counter)) * (Math.pow(x,2*counter+1))/(factorial);
counter++;
}
System.out.println("Maclaurin series is" +result);
}
}
Here is the output of my code when I entered the number 3.14 for x:
enter a number
3.14
Maclaurin series is-24.935440878754584
As you can see, my output should be 0 , not -24.935330878754583 when I substitute in x=3.14 into the function sin x. What am I doing wrong?
First, you don't want the number of iterations controlled by the value you've entered. You'll want a reasonable number of iterations to be reasonably accurate.
while (counter <= 10) {
Second, your factorial calculation is messed up. You want (2n + 1)! each loop, and you still want the first loop to have 1!. Change the calculation to include a factor of 2n and a factor of (2n + 1), and move the factorial calculation after the result addition, to set it up for the next loop. You'll also want the first term to be positive, so use counter + 1 as the exponent in the sign determination.
result = result + (Math.pow(-1, counter + 1)) *
(Math.pow(x, 2 * counter - 1)) / (factorial);
factorial = factorial * (2 * counter) * (2 * counter + 1);
counter++;
}
(Edit: Changed Math.pow(x, 2 * counter + 1) to Math.pow(x, 2 * counter - 1), because counter already starts at 1.)
Sample output:
enter a number
3.14
Maclaurin series is 0.001592652393160744
More:
enter a number
3.14159
Maclaurin series is 2.6530608840492444E-6
More:
enter a number
1.57079
Maclaurin series is 0.9999999999799855