Ok this code was in another question but I couldn't work out how to add my updated code. I got this code working and putting out the right answers but it isn't stopping according to my while loop conditions. i'm not sure what I've done wrong there? The answer clearly converges and all values are right, just while loop is ignored.
/* Newton Raphson Method*/
import java.util.Scanner;
import static java.lang.Math.*;
public class NewtRaphEx {
// Creating Function f = x - cos(3.5x)
double f = 0.0;
double df = 0.0;
public static double function(double x) {
return (x - cos(3.5 * x));
}
public static double dfunction (double x) {
return (1 + 3.5*sin(3.5 * x));
}
public static void main (String[] args) {
//Initialising all variables
double xn = 0.06;
double xnew = 0.0;
double e_allow = 0.001;
double fn = 0.0;
double eps = 0.0;
double dfn = 0.0;
double dx = 0.0;
int n = 0;
int nMax = 10000;
do {
for (n = 0; n <= nMax; n++) {
fn = function(xn);
dfn = dfunction(xn);
dx = -(fn / dfn);
xnew = xn + dx;
xn = xnew;
eps = abs(dx / xn);
n = n + 1;
}
} while (eps <= e_allow || n < nMax);
System.out.print("N" + "\t" + "X" + "\t" + "F(x)" + "\t" + "dF(x)" + "\t");
System.out.println("delX" + "\t" + "X_new" + "\t" + "Epsilon");
System.out.format("%d\t" + "%.3f\t" + "%.3f\t" + "%.3f\t" + "%.3f\t" + "%.3f\t" + "%.3f", n, xn, fn, dfn, dx, xnew, eps);
}
}
The expression
eps <= e_allow || n < nMax
evaluates to true when you reach it, therefore the for loop will run again, setting n = 0 and thus the infinite loop.
Specifically, you would have:
eps = 0.0;
e_allow = 0.001;
n = 10002; // due to the increment inside the loop
nmax = 10000;
as as such:
eps <= e_allow || n < nMax
0.0 <= 0.001 (true) OR 10002 <= 10000 (false) -> true
Related
So here is my code, I am trying to calculate the area of a wave:
public class coefficient {
public static void main (String[] args) {
double f[] = {14.0,18.7,9,4.1,6.7,6,6.3,8.4,4,2.9};
double T = 10;
double area = 0;
int n = 5;
double w = 2 * Math.PI / T;
for (int i = 1; i <= n; i++) {
System.out.println("n = " + i);
for (int t = 0; t < f.length; t++) {
System.out.println("T = " + t + " .......... " + f[t] * Math.cos(i*(w * t)));
area += f[t] * Math.cos(i*(w * t));
}
System.out.printf("\nTotal Area: \t\t%.2f\n", area);
System.out.printf("Calculated area: \t%.2f\n\n", (2/T)*area);
}
}
}
So my outputs are correct, except for my total and calculated areas, which are RIGHT when i=1, but after that they don't give me the right answer.
Here's the thing though - when I manually input "i":
area += f[t] * Math.cos(1*(w * t)); OR
area += f[t] * Math.cos(2*(w * t));
I get the right areas! So I think there's something wrong with my for-loop, but I'm not sure what...
So when i = 1, my area output = 15.11. That is correct. Now, when i = 2 in my loop, I SHOULD get 10.06 but instead I'm getting 25.17. I get the correct answer when I manually change i, so i isn't being defined in that line. But it is in the line above it.
Maybe it's because you aren't setting area back to 0 after each iteration. Move the declaration of area into the for loop, and see if that workd.
double f[] = {14.0,18.7,9,4.1,6.7,6,6.3,8.4,4,2.9};
double T = 10;
int n = 5;
double w = 2 * Math.PI / T;
for (int i = 1; i <= n; i++) {
double area = 0;
System.out.println("n = " + i);
for (int t = 0; t < f.length; t++) {
System.out.println("T = " + t + " .......... " + f[t] * Math.cos(i*(w * t)));
area += f[t] * Math.cos(i*(w * t));
}
System.out.printf("\nTotal Area: \t\t%.2f\n", area);
System.out.printf("Calculated area: \t%.2f\n\n", (2/T)*area);
}
I am writing a Java program for Simpson's method. The basic program works as expected, although I cannot get the (absolute) error part to work.
I think I need to reference my while (absError < 0.000001) loop differently. What am I doing wrong?
First try
public static double function(double x, double s) {
double sech = 1 / Math.cosh(x); // Hyperbolic cosecant
double squared = Math.pow(sech, 2);
return ((Math.pow(x, s)) * squared);
}
// Simpson's rule - Approximates the definite integral of f from a to b.
public static double SimpsonsRule(double a, double b, double s, int n) {
double dx, x, sum4x, sum2x;
double absError = 1.0;
double simpson = 0.0;
double simpson2 = 0.0;
dx = (b-a) / n;
sum4x = 0.0;
sum2x = 0.0;
// 4/3 terms
for (int i = 1; i < n; i += 2) {
x = a + i * dx;
sum4x += function(x,s);
}
// 2/3 terms
for (int i = 2; i < n-1; i += 2) {
x = a + i * dx;
sum2x += function(x,s);
}
// Compute the integral approximation.
simpson = function(a,s) + function(a,b);
simpson = (dx / 3)*(simpson + 4 * sum4x + 2 * sum2x);
while ( absError < 0.000001)
{
simpson2 = SimpsonsRule(a, b, s, n);
absError = Math.abs(simpson2 - simpson) / 15;
simpson = simpson2;
n++;
}
System.out.println("Number of intervals is " + n + ".");
return simpson2;
}
This doesn't work since I did not write
simpson2 = SimpsonsRule(a, b, s, n);
correctly.
I tried doing this a second way, but the solution ultimately also fails.
public static double function(double x, double s) {
double sech = 1 / Math.cosh(x); // Hyperbolic cosecant
double squared = Math.pow(sech, 2);
return ((Math.pow(x, s)) * squared);
}
// Simpson's rule - Approximates the definite integral of f from a to b.
public static double SimpsonsRule(double a, double b, double s, int n) {
double dx, x, sum4x, sum2x;
double absError = 1.0;
double simpson = 0.0;
double simpson2 = 0.0;
dx = (b-a) / n;
sum4x = 0.0;
sum2x = 0.0;
// 4/3 terms
for (int i = 1; i < n; i += 2) {
x = a + i * dx;
sum4x += function(x,s);
}
// 2/3 terms
for (int i = 2; i < n-1; i += 2) {
x = a + i * dx;
sum2x += function(x,s);
}
// Compute the integral approximation.
simpson = function(a,s) + function(a,b);
simpson = (dx / 3)*(simpson + 4 * sum4x + 2 * sum2x);
while ( absError < 0.000001)
{
n++;
dx = (b-a) / n;
// 4/3 terms
for (int i = 1; i < n; i += 2) {
x = a + i * dx;
sum4x += function(x,s);
}
// 2/3 terms
for (int i = 2; i < n-1; i += 2) {
x = a + i * dx;
sum2x += function(x,s);
}
simpson = function(a,s) + function(a,b);
simpson2 = (dx / 3)*(simpson + 4 * sum4x + 2 * sum2x);
absError = Math.abs(simpson2 - simpson) / 15;
simpson = simpson2;
}
System.out.println("Number of intervals is " + n + ".");
return simpson2;
}
I need to write the while loop differently. What is wrong with the way the error is referenced inside the while loop?
The java code up until
while ( absError < 0.000001)
{
simpson2 = SimpsonsRule(a, b, s, n);
absError = Math.abs(simpson2 - simpson) / 15;
simpson = simpson2;
n++;
}
System.out.println("Number of intervals is " + n + ".");
return simpson2;
Works fine and correctly calculates Simpson's method.
Looks like your Simpson's method implementation is not converging. The easiest thing you can do to avoid infinite cycle in while - you have to add another condition - maximum number of iterations.
Something like that:
int n = 0;
while (error < ACCURACY && n++ < MAX_ITERATIONS) {
// while body
}
where ACCURACY is 0.000001 in your case (or 1e-6) and MAX_ITERATIONS is an integer constant, for example 100000 or 1e+6.
Why your algorithm is not converging - this is another question - look carefully on your formulas - use debugging tools. Good luck!
I fixed it. Thanks for your help.
// Simpson's rule - Approximates the definite integral of f from a to b.
public static double SimpsonsRule(double a, double b, double s, int n) {
double simpson, dx, x, sum4x, sum2x;
dx = (b-a) / n;
sum4x = 0.0;
sum2x = 0.0;
// 4/3 terms
for (int i = 1; i < n; i += 2) {
x = a + i * dx;
sum4x += function(x,s);
}
// 2/3 terms
for (int i = 2; i < n-1; i += 2) {
x = a + i * dx;
sum2x += function(x,s);
}
// Compute the integral approximation.
simpson = function(a,s) + function(a,b);
simpson = (dx / 3)*(simpson + 4 * sum4x + 2 * sum2x);
return simpson;
}
// Handles the error for for f(x) = t^s * sech(t)^2. The integration is
// done from 0 to 100.
// Stop Simspson's Method when the relative error is less than 1 * 10^-6
public static double SimpsonError(double a, double b, double s, int n)
{
double futureVal;
double absError = 1.0;
double finalValueOfN;
double numberOfIterations = 0.0;
double currentVal = SimpsonsRule(a,b,s,n);
while (absError / currentVal > 0.000001) {
n = 2*n;
futureVal = SimpsonsRule(a,b,s,n);
absError = Math.abs(futureVal - currentVal) / 15;
currentVal = futureVal;
}
// Find the number of iterations. N starts at 8 and doubles every iteration.
finalValueOfN = n / 8;
while (finalValueOfN % 2 == 0) {
finalValueOfN = finalValueOfN / 2;
numberOfIterations++;
}
System.out.println("The number of iterations is " + numberOfIterations + ".");
return currentVal;
}
I have unfinished code to find the points of intersection of all lines that are perpendicular. So far I have this:
import java.util.Scanner;
public class CountSquares {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int lines = scan.nextInt();
scan.nextLine();
double[][] lineMXYC = new double[4][lines]; // stores the slope, and x
// and y co-ordinates and c
// so the line can be
// represented as y = mx + c
double x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0;
double slope = 0.0;
for (int i = 0; i < lines; i++) {
String input = scan.nextLine();
String[] arrayOfInput = input.split(" ");
x1 = Integer.parseInt(arrayOfInput[0]);
y1 = Integer.parseInt(arrayOfInput[1]);
x2 = Integer.parseInt(arrayOfInput[2]);
y2 = Integer.parseInt(arrayOfInput[3]);
if (x1 == x2)
slope = Double.POSITIVE_INFINITY;
else
slope = (y2 - y1) / (x2 - x1);
lineMXYC[0][i] = slope;
lineMXYC[1][i] = x1;
lineMXYC[2][i] = y1;
lineMXYC[3][i] = y1 - (slope * x1);
}
for (int j = 0; j < lines - 1; j++) { //sorts the array by slopes
if (lineMXYC[0][j] > lineMXYC[0][j + 1]) {
double TEMP = lineMXYC[0][j + 1];
lineMXYC[0][j + 1] = lineMXYC[0][j];
lineMXYC[0][j] = TEMP;
}
}
double[] pointsOfIntersectionX = new double[(int) (lines * lines / 4) + 1]; //max number of points there can be
double[] pointsOfIntersectionY = new double[(int) (lines * lines / 4) + 1];
int count = 0;
for (int k = 0; k < lines; k++) {
for (int n = k; n < lines; n++) {
System.out.println(n + " " + k);
if (1 / lineMXYC[0][k] == -lineMXYC[0][n]) {
double m1 = lineMXYC[0][k];
double m2 = lineMXYC[0][n];
double c1 = lineMXYC[3][k];
double c2 = lineMXYC[3][n];
System.out.println("m1: "+m1);
System.out.println("m2: "+m2);
System.out.println("c1: "+c1);
System.out.println("c2: "+c2);
pointsOfIntersectionX[count] = (c1 - c2) / (m2 - m1); //determinate to find x co-ordinate
pointsOfIntersectionY[count] = (m2 * c1 - m1 * c2)
/ (m2 - m1);
System.out.println("The lines intersect at: ("
+ pointsOfIntersectionX[count] + ", "
+ pointsOfIntersectionY[count] + ")");
count++;
}
}
}
scan.close();
}
}
This will take in the number of lines, then two points on each line seperated by spaces. If I enter
2
3 -1 0 8
3 -1 0 -2
It works fine, finding the point (3, -1)
However, if I put in the same values reversed
2
3 -1 0 -2
3 -1 0 8
It gives me (-3.0, 6.999999999999999) which is wrong
What is going wrong with the code? I can't pinpoint where the problem comes from.
Sorting by slopes may mix your input data in your version.
If you want to swap the lines, swap all line data:
for (int j = 0; j < lines - 1; j++) { //sorts the array by slopes
if (lineMXYC[0][j] > lineMXYC[0][j + 1]) {
for (int i = 0; i < 4; i++) {
double TEMP = lineMXYC[i][j + 1];
lineMXYC[i][j + 1] = lineMXYC[i][j];
lineMXYC[i][j] = TEMP;
}
}
}
If I may give you an advice:
make a separate Line class for better design
implement the compare method or a line comparator
use some sorting algorithm, the one you use will not sort correctly for more lines, e.g. see Java Tutorials
Diophantine reciprocals III
In the following equation x, y, and n are positive integers.
1/x + 1/y = 1/n
For a limit L we define F(L) as the number of solutions which satisfy x < y ≤ L.
We can verify that F(15) = 4 and F(1000) = 1069.
Find F(10^12).
The equation is equivalent to z = xy/(x + y). Let d = gcd(x, y). Then
x = dm, y = dn, with gcd(m, n) = 1.
It follows that gcd(mn, m + n) = 1 so that
z = dmn / (m + n),
which implies (m + n) | d, i.e., d = k(m + n), k a positive integer.
Thus we obtain the solutions:
x = km(m + n), y = kn(m + n), z = kmn,
where the three parameters k, m, n are positive integers.
For I/p=15 I am getting o/p=4 & for I/p=1000 I am getting o/p=1069 in 18sec but for I/p=10^12 no o/p is being displayed. How to handle such huge I/p?
public class testClient {
public static void main(String[] args) {
System.out.println(diophantineReciprocals(1000.0));
}
private static double diophantineReciprocals(double L) {
double noOfSolutions = 0;
double d = 1;
double m = 1;
double n = 1;
double z = 0;
for (double x = 1; x < L; x++) {
for (double y = x + 1; y <= L; y++) {
d = gcd(x, y);
m = x / d;
n = y / d;
x = d * m;
y = d * n;
z = m * n * d / (m + n);
if (/* z == (x * y) / (x + y) && */Math.round(z) != 0
&& (z - Math.round(z)) == 0) {
noOfSolutions++;
}
}
}
return noOfSolutions;
}
private static double gcd(double x, double y) {
double gcd = 1;
for (double i = 2; i <= x; i++) {
if (x % i == 0 && y % i == 0) {
if (i > gcd) {
gcd = i;
}
}
}
return gcd;
}
}
i am trying to not import the math class to use but i am still trying to estimate the constant "e". it is said e= 1+(1/1!)+(1/2!)+(1/3!)+(1/4!)+(1/5!)+.....
these are what i have int at the top
String userInput;
int uIp; // this converts the string into int type
double e = 2;
then i ask some questions then i check to see not zero to exit and non negative to continue
While(uIp >0){
final int endTheLoop = 15;
int factorialNumber = 1;
double e2TheUserInput=0;
for(int i = 2; i < endTheLoop; i++){
for(int j = 1; j < i; j++){
factorialNumber = ((i - 1) * factorialNumber);
}
e = (1/factorialNumber) + e;
e2TheUserInput = Math.pow(e,uIp);
}
}
You are doing integer division(but e is a double right?):
e = (1/factorialNumber) + e;
Correct that to:
e = (1.0/(double)factorialNumber) + e;
It was counting all the loops, but changes are zero according to the integer division. :)
e= 2+(0)+(0)+(0)+(0)+.....
I am not sure what your code is trying to do but if you want to compute exp(x) this is how I would do it.
public static void main(String... args) {
for (int i = -4; i <= 4; i++)
System.out.println(i + ": " + exp(i) + " cf " + Math.exp(i));
}
private static double exp(double d) {
if (d < 0)
return 1 / exp(-d);
double e = 1, term = 1;
for (int i = 1; i < 20 || term > e * 1e-16; i++) {
term *= d / i;
e += term;
}
return e;
}
For large exponents, it more efficient to evaluate the integral powers without using a taylor series.
public static final double E = 2.7182818284590452354;
private static double exp(double d) {
if (d < 0)
return 1 / exp(-d);
long num = (long) d;
double numE = 1;
double mult = E;
while (num > 0) {
if ((num & 1) != 0)
numE *= mult;
num >>>= 1;
mult *= mult;
}
double fract = d - (long) d;
double fractE = 1, term = 1;
for (int i = 1; i < 20; i++) {
term *= fract / i;
fractE += term;
}
return numE * fractE;
}