Trying to estimate e^x with loops - java

I've been staring at this for a few hours, and I can't seem to figure out why my outputs are coming out too small. My outputs do what you'd expect, level off, they just level off to the wrong value. I'm very certain the error lies within the while loop of my main method, or the nested for loop, but I'll go ahead and post everything incase it is hiding somewhere else.
The purpose of this program is to estimate the value of e^x by summing 1 + x + x^2/2! + x^3/3! + ... + x^n/n!. It needs to output the sum for n take to each value between 1 and 10, along with the values of 50 and 100. So 12 outputs all together.
import java.io.*;
import java.text.DecimalFormat;
public class Ch3Ex7
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static double x = 0;
static DecimalFormat df = new DecimalFormat("0.00");
public static void main (String[] args)
{
mainMenu();
int counter = 1;
double heldx = x;
double holderx = 0;
double denom = 1;
double printx = 0;
double f = 1;
while (counter != 100)
{
x = x*heldx;
denom++;
for(int i = 2; i<=denom; i++)
{
f = f*i;
}
holderx = holderx + x/f;
if ((counter > 0 && counter <= 10) || (counter == 50))
{
printx = 1 + heldx + holderx;
System.out.println(df.format(printx));
}
counter++;
}
System.out.println(df.format(printx));
f = 0;
x = 0;
counter = 1;
denom = 1;
callMain();
}
public static void mainMenu()
{
try
{
System.out.println("Requesting user input, press 0 to leave");
x = Integer.parseInt(br.readLine());
space();
if (x == 0)
{
System.exit(0);
}
}
catch(IOException ioe) {}
}
public static void callMain()
{
String[] x = {"A" , "B"};
Ch3Ex7.main(x);
}
public static void space()
{
System.out.println();
}
}

The problem is with your "f" variable. You're trying to calculating the value every time, but you end up starting with your old value.
Get rid of that for loop and add f *= denom; in its place.

Related

Java: While Loop still running even when the condition is false

I'm fairly new at coding and in java in general but I'm hoping that I could get this figured out. I have a do while loop and inside that, I have a while statement if the incorrect value is input in the Scanner. However, when I run the code it always runs the while command once regardless of whether it is incorrect or correct and then runs the code correctly.
import java.util.Scanner;
public class Practice {
public static void main (String [] args) {
int x = 0;
int i = 0;
int n = 0;
String S1 = "";
Scanner user = new Scanner(System.in);
do
{
System.out.println("Enter an integer between 1 and 15: ");
x = user.nextInt();
while ( x < 1 || x > 15);
{
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
n = 1;
}
while (n != 1);
for (i = 1; i <= x; i++)
{
S1 = S1 + "X";
}
for (n = 1; n <= x; n++)
{
System.out.println(S1);
}
}
}
Thank you so much in advance.
Remove the extra ; from your while loop
Like this:
while ( x < 1 || x > 15){
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
while ( x < 1 || x > 15);
The Semi-Colon will terminate the logic and the control will pass to the next line always. Be careful while you code :D
Remove the extra semicolon in the while.
Also close the scanner object(user).
Check the updated code.
public class Practice {
public static void main(String[] args) {
int x = 0;
int i = 0;
int n = 0;
String S1 = "";
Scanner user = new Scanner(System.in);
do {
System.out.println("Enter an integer between 1 and 15: ");
x = user.nextInt();
while (x < 1 || x > 15)
{
System.out.println("Incorrect integer. Must be between 1 and 15. Try again: ");
x = user.nextInt();
}
n = 1;
} while (n != 1);
for (i = 1; i <= x; i++) {
S1 = S1 + "X";
}
for (n = 1; n <= x; n++) {
System.out.println(S1);
}
user.close();
}
}

Java Program to determine value of nested radical constant with 10^-6 precision

Nested radical constant is defined as:
I am writing a Java program to calculate the value of nested radical constant with 10^-6 precision and also print the number of iterations required to get to that precision. Here is my code:
public class nested_radical {
public nested_radical() {
int n = 1;
while ((loop(n) - loop(n - 1)) > 10e-6) {
n++;
}
System.out.println("value of given expression = " + loop(n));
System.out.println("Iterations required = " + n);
}
public double loop(int n) {
double sum = 0;
while (n > 0) {
sum = Math.sqrt(sum + n--);
}
return (sum);
}
public static void main(String[] args) {
new nested_radical();
}
}
This code does what it is supposed to but it is slow. What should I do to optimize this program? Can someone suggest another possible way to implement this program?
I also want to write a same kind of program in MATLAB. It would be great if someone could translate this program into MATLAB too.
I have made some changes in this code and now it stores the value of loop(n - 1) instead of computing it every time. Now this program seems much optimized than before.
public class nested_radical {
public nested_radical() {
int n = 1;
double x = 0, y = 0, p = 1;
while ( p > 10e-6) {
y=x; /*stored the value of loop(n - 1) instead of recomputing*/
x = loop(n);
p = x - y;
n++;
}
System.out.println("value of given expression = " + x);
System.out.println("Iterations required = " + n);
}
public double loop(int n) {
double sum = 0;
while (n > 0) {
sum = Math.sqrt(sum + n--);
}
return (sum);
}
public static void main(String[] args) {
new nested_radical();
}
}
I also successfully translated this code in MATLAB. Here is the code for MATLAB:
n = 1;
x = 0;
p = 1;
while(p > 10e-6)
y = x;
sum = 0;
m=n;
while (m > 0)
sum = sqrt(sum + m);
m = m - 1;
end
x = sum;
p = (x-y);
n = n + 1;
end
fprintf('Value of given expression: %.16f\n', x);
fprintf('Iterations required: %d\n', n);

Exception in thread "main" line 37

I'm getting a "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at WeatherAnalysis.main(WeatherAnalysis.java:37)" Im not sure what is wrong at line 37, date[CurrentLine][0] = (int)fullDate % 100;. Trying to use .txt file to output weather patterns from 1941 to 2013.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WeatherAnalysis {
public static void main(String[] args) throws FileNotFoundException {
int NumberOfDays = 0;
String station;
File f = new File("PortlandWeatherCut.txt"); //Import text file.
Scanner input= new Scanner(f);
input.nextLine();
input.nextLine();
while (input.hasNextLine()) { //Assign number of days to be
NumberOfDays++;
input.nextLine();
}
double[][] date = new double[NumberOfDays][3];
double[] prcp = new double[NumberOfDays];
double[] snow = new double[NumberOfDays];
double[] snwd = new double[NumberOfDays];
double[] tmax = new double[NumberOfDays];
double[] tmin = new double[NumberOfDays];
int CurrentLine = 0;
double fullDate = 0.0;
File g = new File("PortlandWeather.txt"); //Import text file.
Scanner weather= new Scanner(g);
weather.nextLine(); weather.nextLine();
while(weather.hasNextLine()) { //variables and converts to inches.
station = weather.next();
fullDate = weather.nextDouble();
date[CurrentLine][0] = (int)fullDate % 100;
date[CurrentLine][1] = ((int)fullDate % 10000) / 100;
date[CurrentLine][2] = (int)fullDate / 10000;
prcp[CurrentLine] = weather.nextDouble()* .00393701;
snow[CurrentLine] = weather.nextDouble()* 0.0393701;
snwd[CurrentLine] = weather.nextDouble()* 0.0393701;
tmax[CurrentLine] = (weather.nextDouble() / 10.0) * (9.0/5.0) + 32.0;
tmin[CurrentLine] = (weather.nextDouble() / 10.0) * (9.0/5.0) + 32.0;
CurrentLine++;
weather.nextLine();
}
int indexPoint = 0;
int nextPoint = 1;
int endPoint = 0;
for (int x = 1; x < date.length; x++){
//loop that calculates array section to be averaged,
//uses a method to average them, then prints a table
do {
nextPoint++;
endPoint++;
}
while(((int)date[nextPoint - 1][02] / 10) == ((int)date[nextPoint][1] / 10));
if ( nextPoint < date.length) {
System.out.printf("%4.0f's Average Max Temp = %4.1f\tAverage Min Temp = %4.1f\n",
date[indexPoint][02],arrayAvg(tmax, indexPoint, endPoint),
arrayAvg(tmin, indexPoint, endPoint));
indexPoint = nextPoint;
} else
System.out.println();
}
}
public static double arrayAvg(double a[], int fromIndex, int toIndex) {
//Averages the values between the entered parameters and returns it.
double sum = 0;
double divisor = 0;
for (int i = fromIndex; i < toIndex; i++){
if (a[i] == 393.6616299) {
divisor++;
} else {
sum += a[i];
divisor++;
}
}
double average = sum / divisor;
return average;
}
}
Seems like your issue is at line 37. I think that is the
date[currentline][0] = (int)fullDate%100
Inside of your while loop. The loop continues above the NumberOFdAYS that the date 2-dimensional array was created with, therefore it throws out of bout.
My first advise is to break down this monster function into smaller function (Look up Single Responsibility principle).
My second advise is to do TDD (Test driven development)
But if you want a quick and dirty debug, do the following at the beginning of your while loop:
System.out.printf("Current line = %d, does weather has next line? = %b", CurrentLine, weather.hasNextLine)
This will show you all the values of currentLine before the exception and shows the value of your boolean.

Pi with Nilakantha method

I am trying to calculate pi with the Nilakantha method. Whenever I run this program I get -Infinity if I input 1 and anything else I get NaN.
I am trying to modify my program that uses the Leibniz method, and I'm very new to java.
I appreciate all help!
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of calculations you would like to do");
long no = Long.parseLong(reader.readLine());
long cycle = 0;
long w = 2;
long x = 3;
long y = 4;
long z = 4;
long odd=1;
long i=1;
long a = 1;
long b = 1;
double pi= 0.0;
for(;i<=no;i++)
{
a = w*x*y;
b = x*y*z;
double currentTerm=0.0;
if (i%2==0)
{
currentTerm=(double)4/a;
cycle = cycle+1;
w = w+1;
x = x+1;
y = y+1;
}
else
{
currentTerm=(double)-4/b;
cycle = cycle+1;
x = x+1;
y = y+1;
z = z+1;
}
odd=odd+2;
pi = pi+currentTerm;
}
System.out.println("You calculated that pi is");
System.out.println(pi);
System.out.println(3.1415926535897932);
System.out.println("Pi is actually");
double error = pi/3.1415926535897932;
if(error >= 1) {
double bigerror=2-error;
System.out.println("Your accuracy is");
System.out.println(bigerror*100);
System.out.println("percent");
System.out.println(cycle);
}
else {
System.out.println("Your accuracy is");
System.out.println(error*100);
System.out.println("percent");
System.out.println(cycle);
}
}
}
On your first iteration a and b are both zeros.
I don't think you have your initialization part correct.
http://helloacm.com/two-simple-equations-to-compute-pi/
Here I see that j starts from 2.
You have zeroes.
Make sure you implement the algorithm correctly.
Here is your code corrected.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MainProgram {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of calculations you would like to do");
long no = Long.parseLong(reader.readLine());
long step = 0;
double ans = 3;
long j = 2;
double pi = 0.0;
while (true) {
step++;
if ((step % 2) == 1) {
ans += 4.0 / (1.0 * j * (j + 1) * (j + 2));
} else {
ans -= 4.0 / (1.0 * j * (j + 1) * (j + 2));
}
j += 2;
pi = ans;
if (step >= no)
break;
}
System.out.println("You calculated that pi is");
System.out.println(pi);
System.out.println("Pi is actually");
System.out.println(3.1415926535897932);
double error = pi / 3.1415926535897932;
if (error >= 1) {
double bigerror = 2 - error;
System.out.print("Your accuracy is: ");
System.out.print(bigerror * 100);
System.out.println(" percent");
System.out.println(step);
} else {
System.out.print("Your accuracy is: ");
System.out.print(error * 100);
System.out.println(" percent.");
System.out.println(step);
}
}
}

3n + 1 failed for unknown reason

I am doing the programming challenges of which I am doing the 3n + 1 challenge. I ahve completed code for it and it works fine for me completely BUT on the website it keeps saying that I have the wrong answer.I have no idea why if anyone can give me a reason for this it would be a great help. Code is below.
import java.util.*;
import java.io.*;
class Conjecture {
public static void main(String[] args) throws IOException {
int array[] = new int[8];
int finalCounter = 0;
int currentCounter = 0;
Scanner scanner = null;
try {
scanner = new Scanner(
new BufferedReader(new FileReader("text.txt")));
int counter = 0;
while (scanner.hasNext()) {
array[counter] = scanner.nextInt();
counter++;
}
} finally {
if (scanner != null) {
scanner.close();
System.out.println("done");
}
}
for (int loop = 0; loop < array.length; loop += 2) {
int i = array[loop];
int j = array[loop + 1];
finalCounter = 0;
for (int k = i; k < j; k++) {
int x = k;
currentCounter = 0;
while (x != 1) {
if (x % 2 == 0) {
x = x / 2;
currentCounter++;
} else if (x % 2 == 1) {
x = x * 3 + 1;
currentCounter++;
}
if (currentCounter > finalCounter) {
finalCounter = currentCounter;
}
}
}
System.out.println(i + " " + j + " " + (finalCounter + 1));
}
}
}
Instead of reading from file.txt, you should read the input from System.in. Since the problem statement does not says the number of test cases, you should process each case at the moment of reading the case. Your array is just 8 elements long, and I'm pretty sure there is going to be more test cases.

Categories