Taylor series. Program does fewer iterations - java

So I am required to recursively calculate e^x using a factored form of a Taylor series:
equation: e^x = 1 +x + (x^2)/2! + ... + ((x^n)/n!))
U(n) = U(n-1)*(x/n)
break point |U(n)| < eps
package lab2;
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
System.out.println("Enter x: ");
int x = in.nextInt();
System.out.println("Enter 0 < e < 1: ");
double e = in.nextDouble();
double result = 1.0;
int n = 1;
double U = x / n;
while (Math.abs(U) >= e)
{
double fa = 1;
for (int i = 1; i <= n; i++)
fa *= i;
result += Math.pow(x, n) / fa;
U *= x / ++n;
}
System.out.println("e^x = " + result);
}
}
It works only x+1 times and then debug says U equals 0 and its our break point. I can't get why this happens. Can you please help me?

Since x and n are integer, dividing them will be done using integer division. Only after the division is down is the result promoted to a double in order to store in U. In order to perform floating point division you could either define x as a double or explicitly cast it when you divide:
double U = ((double) x) / n;

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.

Calculating Average and Standard Deviation using do while loop

I am trying to write a program which asks the user for a series of positive values and computes the mean and standard deviation of those values having the input stop when the user enters -1. I seem to have the average part down however. I can't seem to get the standard deviation.
So far this is what I have.
import java.util.Scanner;
public class HW0402
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double x;
double sum = 0;
double average = 0;
double dev = 0;
double var = 0;
double sqrx = 0;
int n = 0;
do
{
System.out.println("Enter positive values, enter -1 to end");
x = input.nextInt();
if (x == -1)
{
break;
}
sum += x;
n++;
average = sum / n;
sqrx += Math.pow(x-average,2);
var = sqrx / (n-1);
dev = Math.sqrt(var);
} while (x != -1);
System.out.println("Average: " + average);
System.out.println("Deviation: " + dev);
}
}
I seem to get odd results such as decimals when simply calculating sqrx += x- average
I'm new to java and haven't leaned alternatives to this problem, I would love it if someone pointed me in the right direction on what I should do, or explain what I did wrong.
Apologies ahead of time for any novice mistakes I made.
int n = 0;
int K = 0;
double Sum = 0;
double Sum_sqr = 0;
do {
System.out.println("Enter positive values, enter -1 to end");
x = input.nextInt();
if (x == -1)
{
break;
}
if ( n == 0 ) K = x;
n++;
Sum += (x - K);
Sum_sqr += (x - K) * (x - K);
} while (x != -1);
double mean = K + Sum / n;
double varPop = (Sum_sqr - (Sum*Sum)/n) / (n);
double varSample = (Sum_sqr - (Sum*Sum)/n) / (n-1);
double devPop = Math.sqrt(varPop);
double devSample = Math.sqrt(varSample);
Reference Wikipedia: Computing Shifted Data. Also, Population or Sample, makes a difference.

Return how many terms are necessary entering a level of precision, e.g .001, to come within the specified precision of the value of PI?

Problem: Interactively enter a level of precision, e.g., .001, and then report how many terms are necessary for each of these estimates to come within the specified precision of the value of pi.
My Solution So Far:
Current result does not terminate. The PIEstimator class driver is given. The problem lies inside the PIEstimates class. Some specific questions that I have:
How do you calculate Wallis PI and Leibniz PI in code? The ways for calculating each arithmetically for Wallis is:
pi/4 = (2/3)(4/3)(4/5)(6/5)(6/7)(8/7)(8/9)*...
and for Leibniz:
pi/4 = (1 - 1/3 + 1/5 - 1/7 + 1/9 ...)
Is the current logic of doing this code correct so far? Using a while loop to check if the respective PI calculation is within the limits, with a for loop inside continuing to run until the while requirements are met. Then there is a count that returns the number of times the loop repeated.
For .001, for example, how many terms does it take for each of these formulas to reach a value between 3.14059.. and 3.14259...
import java.util.Scanner;
public class PiEstimator {
public static void main(String[] args) {
System.out.println("Wallis vs Leibnitz:");
System.out.println("Terms needed to estimate pi");
System.out.println("Enter precision sought");
Scanner scan = new Scanner(System.in);
double tolerance = scan.nextDouble();
PiEstimates e = new PiEstimates(tolerance);
System.out.println("Wallis: " + e.wallisEstimate());
System.out.println("Leibnitz: " + e.leibnitzEstimate());
}
}
public class PiEstimates {
double n = 0.0;
double upperLim = 0;
double lowerLim = 0;
public PiEstimates(double tolerance) {
n = tolerance;
upperLim = Math.PI+n;
lowerLim = Math.PI-n;
}
public double wallisEstimate() {
double wallisPi = 4;
int count = 0;
while(wallisPi > upperLim || wallisPi < lowerLim) {
for (int i = 3; i <= n + 2; i += 2) {
wallisPi = wallisPi * ((i - 1) / i) * ((i + 1) / i);
}
count++;
}
return count;
}
public double leibnitzEstimate() {
int b = 1;
double leibnizPi = 0;
int count = 0;
while(leibnizPi > upperLim || leibnizPi < lowerLim) {
for (int i = 1; i < 1000; i += 2) {
leibnizPi += (4/i - 4/i+2);
}
b = -b;
count++;
}
return count;
}
}
At least one mistake in wallisEstimate
for (int i = 3; i <= n + 2; i += 2) {
should be count instead of n:
for (int i = 3; i <= count + 2; i += 2) {
... but still then the algorithm is wrong. This would be better:
public double wallisEstimate() {
double wallisPi = 4;
int count = 0;
int i = 3;
while(wallisPi > upperLim || wallisPi < lowerLim) {
wallisPi = wallisPi * ((i - 1) / i) * ((i + 1) / i);
count++;
i += 2;
}
return count;
}
Similarly, for the Leibniz function:
public double leibnitzEstimate() {
double leibnizPi = 0;
int count = 0;
int i = 1;
while(leibnizPi > upperLim || leibnizPi < lowerLim) {
leibnizPi += (4/i - 4/i+2);
count++;
i += 4;
}
return count;
}
For Leibnitz, I think the inner loop should only run count number of times:
for (int i = 1; i < count; i += 2) {
leibnizPi += (4/i - 4/i+2);
}
If it runs 1000 times every time you can't know when pi was in range.
If the while loops don't terminate, then they don't approach PI.
Wallis: pi/4 = (2/3)(4/3)(4/5)(6/5)(6/7)(8/7)(8/9)*...
The while loop would restart the for loop at i = 3 which would keep adding the same sequence of terms, rather than progressing along with the pattern.
Here's a draft of an alternative solution (no pun intended) based on the pattern of terms.
As you see, the numerators repeat, except for the 2. The divisors repeat aswell, but offset from the numerators: they increment in an alternating fashion.
This way you can actually count each individual terms, instead of pairs of them.
public double wallisEstimate() {
double wallisPi = 1;
int count = 0;
double numerator = 2;
double divisor = 3;
while(wallisPi > upperLim || wallisPi < lowerLim) {
wallisPi *= numerator / divisor;
if ( count++ & 1 == 0 )
numerator+=2;
else
divisor+=2;
}
return count;
}
There is one more change to make, and that is in the initialisation of upperLim and lowerLim. The algorithm approaches PI/2, so:
upperLim = (Math.PI + tolerance)/2;
lowerLim = (Math.PI - tolerance)/2;
Leibniz: pi/4 = (1 - 1/3 + 1/5 - 1/7 + 1/9 ...)
Here the for loop is also unwanted: at best, you will be counting increments of 2000 terms at a time.
The pattern becomes obvious if you write it like this:
1/1 - 1/3 + 1/5 - 1/7 ...
The divisor increments by 2 for every next term.
public double leibnitzEstimate() {
double leibnizPi = 0;
int divisor = 1;
int count = 0;
while(leibnizPi > upperLim || leibnizPi < lowerLim) {
leibnizPi += 1.0 / divisor;
divisor = -( divisor + 2 );
count++;
}
return count;
}
The update of leibnizPi can also be written like this:
leibnizPi += sign * 1.0 / divisor;
divisor += 2;
sign = -sign;
which is more clear, takes one more variable and one more instruction.
An update to the upperLim and lowerLim must be made here aswell: the algorithm approaches PI/4 (different from Leibniz!), so:
upperLim = (Math.PI + tolerance)/4;
lowerLim = (Math.PI - tolerance)/4;

how to get exponents without using the math.pow for java

This is my program
// ************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ************************************************************
import java.util.Scanner;
public class PowersOf2 {
public static void main(String[] args)
{
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent= 1;
double x;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop Scanner
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
//initialize exponent -- the first thing printed is 2 to the what?
while( exponent <= numPowersOf2)
{
double x1 = Math.pow(2, exponent);
System.out.println("2^" + exponent + " = " + x1);
exponent++;
}
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
}
}
The thing is that I am not allowed to use the math.pow method, I need to find another way to get the correct answer in the while loop.
Powers of 2 can simply be computed by Bit Shift Operators
int exponent = ...
int powerOf2 = 1 << exponent;
Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring
Here is a post that allows both negative/positive power calculations.
https://stackoverflow.com/a/23003962/3538289
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
You could implement your own power function.
The complexity of the power function depends on your requirements and constraints.
For example, you may constraint exponents to be only positive integer.
Here's an example of power function:
public static double power(double base, int exponent) {
double ans = 1;
if (exponent != 0) {
int absExponent = exponent > 0 ? exponent : (-1) * exponent;
for (int i = 1; i <= absExponent; i++) {
ans *= base;
}
if (exponent < 0) {
// For negative exponent, must invert
ans = 1.0 / ans;
}
} else {
// exponent is 0
ans = 1;
}
return ans;
}
If there are no performance constraints you can do:
double x1=1;
for(int i=1;i<=numPowersOf2;i++){
x1 =* 2
}
You can try to do this based on this explanation:
public double myPow(double x, int n) {
if(n < 0) {
if(n == Integer.MIN_VALUE) {
n = (n+1)*(-1);
return 1.0/(myPow(x*x, n));
}
n = n*(-1);
return (double)1.0/myPow(x, n);
}
double y = 1;
while(n > 0) {
if(n%2 == 0) {
x = x*x;
}
else {
y = y*x;
x = x*x;
}
n = n/2;
}
return y;
}
It's unclear whether your comment about using a loop is a desire or a requirement. If it's just a desire there is a math identity you can use that doesn't rely on Math.Pow.
xy = ey∙ln(x)
In Java this would look like
public static double myPow(double x, double y){
return Math.exp(y*Math.log(x));
}
If you really need a loop, you can use something like the following
public static double myPow(double b, int e) {
if (e < 0) {
b = 1 / b;
e = -e;
}
double pow = 1.0;
double intermediate = b;
boolean fin = false;
while (e != 0) {
if (e % 2 == 0) {
intermediate *= intermediate;
fin = true;
} else {
pow *= intermediate;
intermediate = b;
fin = false;
}
e >>= 1;
}
return pow * (fin ? intermediate : 1.0);
}
// Set the variables
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent = 0;
/* User input here */
// Loop and print results
do
{
System.out.println ("2^" + exponent + " = " + nextPowerOf2);
nextPowerOf2 = nextPowerOf2*2;
exponent ++;
}
while (exponent < numPowersOf2);
here is how I managed without using "myPow(x,n)", but by making use of "while". (I've only been learning Java for 2 weeks so excuse, if the code is a bit lumpy :)
String base ="";
String exp ="";
BufferedReader value = new BufferedReader (new InputStreamReader(System.in));
try {System.out.print("enter the base number: ");
base = value.readLine();
System.out.print("enter the exponent: ");
exp = value.readLine(); }
catch(IOException e){System.out.print("error");}
int x = Integer.valueOf(base);
int n = Integer.valueOf(exp);
int y=x;
int m=1;
while(m<n+1) {
System.out.println(x+"^"+m+"= "+y);
y=y*x;
m++;
}
To implement pow function without using built-in Math.pow(), we can use the below recursive way to implement it. To optimize the runtime, we can store the result of power(a, b/2) and reuse it depending on the number of times is even or odd.
static float power(float a, int b)
{
float temp;
if( b == 0)
return 1;
temp = power(a, b/2);
// if even times
if (b%2 == 0)
return temp*temp;
else // if odd times
{
if(b > 0)
return a * temp * temp;
else // if negetive i.e. 3 ^ (-2)
return (temp * temp) / a;
}
}
I know this answer is very late, but there's a very simple solution you can use if you are allowed to have variables that store the base and the exponent.
public class trythis {
public static void main(String[] args) {
int b = 2;
int p = 5;
int r = 1;
for (int i = 1; i <= p; i++) {
r *= b;
}
System.out.println(r);
}
}
This will work with positive and negative bases, but not with negative powers.
To get the exponential value without using Math.pow() you can use a loop:
As long as the count is less than b (your power), your loop will have an
additional "* a" to it. Mathematically, it is the same as having a Math.pow()
while (count <=b){
a= a* a;
}
Try this simple code:
public static int exponent(int base, int power) {
int answer = 1;
for(int i = 0; i < power; i++) {
answer *= base;
}
return answer;
}

Evaluating a polynomial with Horner's Algorithm and calculating steps (Java)

I need help on my java code. What I'm trying to accomplish is to calculate the size of each step on a polynomial: double s = (b-a)/nsteps;
The inputs for the polynomial to be created is degree, coefficient, start value of x, stopping value of x, and the number of steps. Whenever I try to run a test, my output is 0 for x and y and I'm not sure what I am missing on my code.
Here is my run test on how its supposed to work, but my result for x and y is 0:
Enter degree:2
Enter coefficient 2:1
Enter coefficient 1:0
Enter coefficient 0:0
f(x) = 1.0x^2 + .0x^1 + 0.0
Enter initial x:0
Enter final x:10
Enter number of steps:20
x = 0.0; f(x) = 0.0
x = 0.5; f(x) = 0.25
x = 1.0; f(x) = 1.0
x = 1.5; f(x) = 2.25
x = 2.0; f(x) = 4.0
x = 2.5; f(x) = 6.25
x = 3.0; f(x) = 9.0
x = 3.5; f(x) = 12.25
x = 4.0; f(x) = 16.0
x = 4.5; f(x) = 20.25
x = 5.0; f(x) = 25.0
x = 5.5; f(x) = 30.25
x = 6.0; f(x) = 36.0
x = 6.5; f(x) = 42.25
x = 7.0; f(x) = 49.0
x = 7.5; f(x) = 56.25
x = 8.0; f(x) = 64.0
x = 8.5; f(x) = 72.25
x = 9.0; f(x) = 81.0
x = 9.5; f(x) = 90.25
x = 10.0; f(x) = 100.0
and here is my java code:
import java.util.*;
public class PolyAreaTwo{
//method evalpoly Horner's rule
public static double evalpoly(double[] c, double x) {
int n = c.length - 1;
double y = c[n];
for (int i = n - 1; i >= 0; i--) {
y = c[i] + (x * y);
}
return y;
}
//main method
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n;
double a, b;
int nsteps;
//input degree
System.out.print("Enter degree of polynomial:");
n = in.nextInt();
//input n+1 coefficients
double[] c = new double[n+1];
for (int i=n; i>=0; i--) {
System.out.print("Enter coefficent " + i + ":");
c[i] = in.nextDouble();
}
for (double d : c) {
System.out.print(" x ^ " + d);
}
//input starting value x = a
System.out.println("Enter starting x: ");
a = in.nextDouble();
//input stopping value x = b
System.out.print("Enter stop x: ");
b = in.nextDouble();
//input number of steps between starting x and stopping x
System.out.print("Enter steps: ");
nsteps = in.nextInt();
//calculate size of each step
double s = (b-a)/nsteps;
int steps = 0;
//loop to call the evalpoly method
for (double x = a; x <= b; x += s) {
double y = evalpoly(c, x);
System.out.println("x ="+x+ " , y ="+y);
}
}
}
After removing the unnecessary outer while loop; consider using your calculated step size in the for loop: x += s.
As an aside, your implementation of Horner's method in evalpoly() can be made more efficient, as shown here and here, by initializing y to the highest order coefficient.
public static double evalpoly(double[] c, double x) {
int n = c.length - 1;
double y = c[n];
for (int i = n - 1; i >= 0; i--) {
y = c[i] + (x * y);
}
return y;
}

Categories