Determine extrema of function - java

I'm running into an issue in which the minima is not being correctly set. The maxima is setting perfectly, but I know that the minima should be less than 0. Running this snippet, it seems like the minima is never being set. Any ideas?
edit: The curve points should be from -1 to 3. Here's an image:
public class FindingExtrema {
public static void main(String[] args) {
double lowestPoint = 0;
double highestPoint = 0;
double y;
double x = -1;
int timesCalculated = 0;
while (x <= 3) {
y = run(x);
if (y < lowestPoint) {
lowestPoint = y;
System.out.printf("y: %1$.5f", y);
}
if (y > highestPoint) {
highestPoint = y;
}
x += .00001;
timesCalculated++;
}
System.out.println("Done!");
System.out.printf("Lowest: %1$.5f, Highest: %2$.5f; Calculated %3$d times\n", lowestPoint, highestPoint, timesCalculated);
}
private static double run(double x) {
return Math.cbrt(2 * x) - Math.sqrt(8 * x) + x + 16;
}
}

but I know that the minima should be less than 0.
It isn't, if you graph it. I plugged your function into Google for the range 0 to 3 and the minimum was something like 15.431.

The expression
Math.cbrt(2 * x) - Math.sqrt(8 * x) + x + 16;
is not equivalent to the right hand side for the equation of your graph - you are getting cube root confused with cubing and square root confused with squaring.
The correct expression is
(2 * x * x * x) - (8 * x * x) + x + 16

Make your lowestPoint point as follows.
double lowestPoint = 1000;
Could you please put the original equation? you can't find square root for minus value.
sqrt
public static double sqrt(double a)
Returns the correctly rounded positive square root of a double value. Special cases: ◦If the argument is NaN or less than zero, then the result is NaN.
◦If the argument is positive infinity, then the result is positive infinity.
◦If the argument is positive zero or negative zero, then the result is the same as the argument.
Otherwise, the result is the double value closest to the true mathematical square root of the argument value.Parameters:a - a value.Returns:the positive square root of a. If the argument is NaN or less than zero, the result is NaN.

Related

How to generate a random double number in Java? (not necessarily in the range [0,1]) [duplicate]

Anyone got an idea of how to achieve this. I've tried the usual formula but I'm only getting positive numbers <= 10:
Double.MIN_VALUE + Math.random() * ((Double.MAX_VALUE - Double.MIN_VALUE) + 1)
You could do this
private static final Random rand = new Random();
public static double getRandomDouble() {
while(true) {
double d = Double.longBitsToDouble(rand.nextLong());
if (d < Double.POSITIVE_INFINITY && d > Double.NEGATIVE_INFINITY)
return d;
}
}
This will return any finite double with equal probability.
You can't just the the formula above as the (Double.MAX_VALUE - (-Double.MAX_VALUE)) overflows to infinity. i.e. the range for all positive and negative double values is too large to store in a double.
double d = Math.random() * Double.MAX_VALUE;
return Math.random() < 0.5 ? d : 0-d;

Approximate a derivative for a continuous function throughout certain step intervals

I am looking to write a method in Java which finds a derivative for a continuous function. These are some assumptions which have been made for the method -
The function is continuous from x = 0 to x = infinity.
The derivative exists at every interval.
A step size needs to be defined as a parameter.
The method will find the max/min for the continuous function over a given interval [a:b].
As an example, the function cos(x) can be shown to have maximum or minimums at 0, pi, 2pi, 3pi, ... npi.
I am looking to write a method that will find all of these maximums or minimums provided a function, lowerBound, upperBound, and step size are given.
To simplify my test code, I wrote a program for cos(x). The function I am using is very similar to cos(x) (at least graphically). Here is some Test code that I wrote -
public class Test {
public static void main(String[] args){
Function cos = new Function ()
{
public double f(double x) {
return Math.cos(x);
}
};
findDerivative(cos, 1, 100, 0.01);
}
// Needed as a reference for the interpolation function.
public static interface Function {
public double f(double x);
}
private static int sign(double x) {
if (x < 0.0)
return -1;
else if (x > 0.0)
return 1;
else
return 0;
}
// Finds the roots of the specified function passed in with a lower bound,
// upper bound, and step size.
public static void findRoots(Function f, double lowerBound,
double upperBound, double step) {
double x = lowerBound, next_x = x;
double y = f.f(x), next_y = y;
int s = sign(y), next_s = s;
for (x = lowerBound; x <= upperBound ; x += step) {
s = sign(y = f.f(x));
if (s == 0) {
System.out.println(x);
} else if (s != next_s) {
double dx = x - next_x;
double dy = y - next_y;
double cx = x - dx * (y / dy);
System.out.println(cx);
}
next_x = x; next_y = y; next_s = s;
}
}
public static void findDerivative(Function f, double lowerBound, double
upperBound, double step) {
double x = lowerBound, next_x = x;
double dy = (f.f(x+step) - f.f(x)) / step;
for (x = lowerBound; x <= upperBound; x += step) {
double dx = x - next_x;
dy = (f.f(x+step) - f.f(x)) / step;
if (dy < 0.01 && dy > -0.01) {
System.out.println("The x value is " + x + ". The value of the "
+ "derivative is "+ dy);
}
next_x = x;
}
}
}
The method for finding roots is used for finding zeroes (this definitely works). I only included it inside my test program because I thought that I could somehow use similar logic inside the method which finds derivatives.
The method for
public static void findDerivative(Function f, double lowerBound, double
upperBound, double step) {
double x = lowerBound, next_x = x;
double dy = (f.f(x+step) - f.f(x)) / step;
for (x = lowerBound; x <= upperBound; x += step) {
double dx = x - next_x;
dy = (f.f(x+step) - f.f(x)) / step;
if (dy < 0.01 && dy > -0.01) {
System.out.println("The x value is " + x + ". The value of the "
+ "derivative is "+ dy);
}
next_x = x;
}
}
could definitely be improved. How could I write this differently? Here is sample output.
The x value is 3.129999999999977. The value of the derivative is -0.006592578364594814
The x value is 3.1399999999999766. The value of the derivative is 0.0034073256197308943
The x value is 6.26999999999991. The value of the derivative is 0.008185181673381337
The x value is 6.27999999999991. The value of the derivative is -0.0018146842631128202
The x value is 9.409999999999844. The value of the derivative is -0.009777764220086915
The x value is 9.419999999999844. The value of the derivative is 2.2203830347677922E-4
The x value is 12.559999999999777. The value of the derivative is 0.0013706082193754021
The x value is 12.569999999999776. The value of the derivative is -0.00862924258597797
The x value is 15.69999999999971. The value of the derivative is -0.002963251265619693
The x value is 15.70999999999971. The value of the derivative is 0.007036644660118885
The x value is 18.840000000000146. The value of the derivative is 0.004555886794943564
The x value is 18.850000000000147. The value of the derivative is -0.005444028885981389
The x value is 21.980000000000636. The value of the derivative is -0.006148510767989279
The x value is 21.990000000000638. The value of the derivative is 0.0038513993028788107
The x value is 25.120000000001127. The value of the derivative is 0.0077411191450771355
The x value is 25.13000000000113. The value of the derivative is -0.0022587599505241585
The main thing that I can see to improve performance in the case that f is expensive to compute, you could save the previous value of f(x) instead of computing it twice for each iteration. Also dx is never used and would always be equal to step anyway. next_x also never used. Some variable can be declare inside the loop. Moving the variable declarations inside improves readability but not performance.
public static void findDerivative(Function f, double lowerBound, double upperBound, double step) {
double fxstep = f.f(x);
for (double x = lowerBound; x <= upperBound; x += step) {
double fx = fxstep;
fxstep = f.f(x+step);
double dy = (fxstep - fx) / step;
if (dy < 0.01 && dy > -0.01) {
System.out.println("The x value is " + x + ". The value of the "
+ "derivative is " + dy);
}
}
}
The java code you based on (from rosettacode) is not OK, do not depend on it.
it's expecting y (a double value) will become exactly zero.
You need a tolerance value for such kind of tests.
it's calculating derivative, and using Newton's Method to calculate next x value,
but not using it to update x, there is not any optimization there.
Here there is an example of Newton's Method in Java
Yes you can optimize your code using Newton's method,
Since it can solve f(x) = 0 when f'(x) given,
also can solve f'(x) = 0 when f''(x) given, same thing.
To clarify my comment, I modified the code in the link.
I used step = 2, and got correct results.
Check how fast it's, compared to other.
That's why optimization is used,
otherwise reducing the step size and using brute force would do the job.
class Test {
static double f(double x) {
return Math.sin(x);
}
static double fprime(double x) {
return Math.cos(x);
}
public static void main(String argv[]) {
double tolerance = .000000001; // Our approximation of zero
int max_count = 200; // Maximum number of Newton's method iterations
/*
* x is our current guess. If no command line guess is given, we take 0
* as our starting point.
*/
double x = 0.6;
double low = -4;
double high = 4;
double step = 2;
int inner_count = 0;
for (double initial = low; initial <= high; initial += step) {
x = initial;
for (int count = 1; (Math.abs(f(x)) > tolerance)
&& (count < max_count); count++) {
inner_count++;
x = x - f(x) / fprime(x);
}
if (Math.abs(f(x)) <= tolerance) {
System.out.println("Step: " + inner_count + ", x = " + x);
} else {
System.out.println("Failed to find a zero");
}
}
}
}

Trouble Computing Pi with Java [duplicate]

This question already has answers here:
Double division behaving wrongly
(4 answers)
Closed 7 years ago.
I have been trying for a few days to compute pi using the series expansion pi = 4(1-1/3+1/5-1/7... but whenever I use the code I have below, it returns 4.0.
public class Pi {
public static void main (String args[]) {
double pie = 0.0;
int max = 1000;
for (int x = 1 ; x < max ; x = x + 2) {
if (x % 4 == 1) {
pie+= 1/x;
} else if (x % 4 == 3) {
pie-=1/x;
}
}
System.out.println(4*pie);
}
}
In this, I am computing pie to a denominator below 1000. Pie is the variable that stores my value created for pie. At the end, it prints pi, but always returns 4.0.
Using the Debug feature in my IDE (Eclipse), I see the value of pie jumps to 4 from the initial value of 0, but then does not change for the rest of the times the program increments the value of x in the for loop, it does not do anything to pi.
You are performing integer division with 1/x, which always results in an int, truncating the true decimal value. 1/1 is 1, but 1 divided by anything larger is 0 in Java, so your result will always be 4.
Use a double literal to force floating-point division.
pie += 1.0 / x; // and pie -= 1.0 / x;
Alternatively, you can cast 1 to a double.
pie += (double) 1 / x; // and pie -= (double) 1 / x;
The problem is that you are performing integer division and adding the result to a double. x is an int and 1 is an int. When you divide an integer by an integer, you get back an integer. Hence what you're adding to pie is always an integer.
The first time you run the loop, you evaluate the expression 1/1, which returns just 1 (an integer) and assigns that value to pie. For everything else after, you get 0, which means that pie doesn't change. Hence when you finally print 4 * pie, you get 4.
There are a few options:
Use double everywhere.
Change pie += 1 / x; to pie += (1.0 / x); (and the same for the other one)
Cast 1 to double before adding to pie: pie += (double) 1 / x.
The problem is that you are making an integer division which returns less than zero. As an integer, the value will be rounded to zero instead. This adds zero to pie on each iteration.
What you need to do is to replace the literal integer ones, to literal floating point ones, like this
package cl.misc.pi;
public class Pi {
public static void main(String args[]) {
double pie = 0.0;
int max = 1000;
for (int x = 1; x < max; x = x + 2) {
if (x % 4 == 1) {
pie += 1.00 / x;
} else if (x % 4 == 3) {
pie -= 1.00 / x;
}
}
System.out.println(4 * pie);
}
}
As you see, I did replace pie += 1 / x for pie += 1.00 / x which now adds a floating point result to pie.
Result of this routine is 3.139592655589785

Comparing a double against zero

I'm new to Java and I've been trying to implement an algorithm for finding the roots of a cubical equation. The problem arises when I calculate the discriminant and try to check where it falls relative to zero.
If you run it and enter the numbers "1 -5 8 -4", the output is as follows:
1 -5 8 -4
p=-0.333333, q=0.074074
disc1=0.001372, disc2=-0.001372
discriminant=0.00000000000000001236
Discriminant is greater than zero.
I know the problem arises because the calculations with doubles are not precise. Normally the discriminant should be 0, but it ends up being something like 0.00000000000000001236.
My question is, what is the best way to avoid this? Should I check if the number falls between an epsilon neighborhood of zero? Or is there a better and more precise way?
Thank you in advance for your answers.
import java.util.Scanner;
class Cubical {
public static void main(String[] args) {
// Declare the variables.
double a, b, c, d, p, q, gamma, discriminant;
Scanner userInput = new Scanner(System.in);
a = userInput.nextDouble();
b = userInput.nextDouble();
c = userInput.nextDouble();
d = userInput.nextDouble();
// Calculate p and q.
p = (3*a*c - b*b) / (3*a*a);
q = (2*b*b*b) / (27*a*a*a) - (b*c) / (3*a*a) + d/a;
// Calculate the discriminant.
discriminant = (q/2)*(q/2) + (p/3)*(p/3)*(p/3);
// Just to see the values.
System.out.printf("p=%f, q=%f\ndisc1=%f, disc2=%f\ndiscriminant=%.20f\n", p, q, (q/2)*(q/2), (p/3)*(p/3)*(p/3), (q/2)*(q/2) + (p/3)*(p/3)*(p/3));
if (discriminant > 0) {
System.out.println("Discriminant is greater than zero.");
}
if (discriminant == 0) {
System.out.println("Discriminant is equal to zero.");
}
if (discriminant < 0) {
System.out.println("Discriminant is less than zero.");
}
}
}
The simplest epsilon check is
if(Math.abs(value) < ERROR)
a more complex one is proportional to the value
if(Math.abs(value) < ERROR_FACTOR * Math.max(Math.abs(a), Math.abs(b)))
In your specific case you can:
if (discriminant > ERROR) {
System.out.println("Discriminant is greater than zero.");
} else if (discriminant < -ERROR) {
System.out.println("Discriminant is less than zero.");
} else {
System.out.println("Discriminant is equal to zero.");
}
Should I check if the number falls between an epsilon neighborhood of
zero?
Exactly
Here's solution that is precise when the input values are integers, though it is probably not the most practical.
It will probably also work fine on input values that have a finite binary representation (eg. 0.125 does, but 0.1 doesn't).
The trick: Remove all divisions from the intermediate results and only divide once at the end. This is done by keeping track of all the (partial) numerators and denominators. If the discriminant should be 0 then it's numerator will be 0. No round-off error here as long as values at intermediate additions are within a magnitude of ~2^45 from each other (which is usually the case).
// Calculate p and q.
double pn = 3 * a * c - b * b;
double pd = 3 * a * a;
double qn1 = 2 * b * b * b;
double qd1 = 27 * a * a * a;
double qn2 = b * c;
double qn3 = qn1 * pd - qn2 * qd1;
double qd3 = qd1 * pd;
double qn = qn3 * a + d * qd3;
double qd = qd3 * a;
// Calculate the discriminant.
double dn1 = qn * qn;
double dd1 = 4 * qd * qd;
double dn2 = pn * pn * pn;
double dd2 = 27 * pd * pd * pd;
double dn = dn1 * dd2 + dn2 * dd1;
double dd = dd1 * dd2;
discriminant = dn / dd;
(only checked on the provided input values, so tell me if something's wrong)
maybe BigDecimal is worth a look at...
http://download.oracle.com/javase/1.4.2/docs/api/java/math/BigDecimal.html
you can secify the round mode in the divide-operation

Newton's method with specified digits of precision

I'm trying to write a function in Java that calculates the n-th root of a number. I'm using Newton's method for this. However, the user should be able to specify how many digits of precision they want. This is the part with which I'm having trouble, as my answer is often not entirely correct. The relevant code is here: http://pastebin.com/d3rdpLW8. How could I fix this code so that it always gives the answer to at least p digits of precision? (without doing more work than is necessary)
import java.util.Random;
public final class Compute {
private Compute() {
}
public static void main(String[] args) {
Random rand = new Random(1230);
for (int i = 0; i < 500000; i++) {
double k = rand.nextDouble()/100;
int n = (int)(rand.nextDouble() * 20) + 1;
int p = (int)(rand.nextDouble() * 10) + 1;
double math = n == 0 ? 1d : Math.pow(k, 1d / n);
double compute = Compute.root(n, k, p);
if(!String.format("%."+p+"f", math).equals(String.format("%."+p+"f", compute))) {
System.out.println(String.format("%."+p+"f", math));
System.out.println(String.format("%."+p+"f", compute));
System.out.println(math + " " + compute + " " + p);
}
}
}
/**
* Returns the n-th root of a positive double k, accurate to p decimal
* digits.
*
* #param n
* the degree of the root.
* #param k
* the number to be rooted.
* #param p
* the decimal digit precision.
* #return the n-th root of k
*/
public static double root(int n, double k, int p) {
double epsilon = pow(0.1, p+2);
double approx = estimate_root(n, k);
double approx_prev;
do {
approx_prev = approx;
// f(x) / f'(x) = (x^n - k) / (n * x^(n-1)) = (x - k/x^(n-1)) / n
approx -= (approx - k / pow(approx, n-1)) / n;
} while (abs(approx - approx_prev) > epsilon);
return approx;
}
private static double pow(double x, int y) {
if (y == 0)
return 1d;
if (y == 1)
return x;
double k = pow(x * x, y >> 1);
return (y & 1) == 0 ? k : k * x;
}
private static double abs(double x) {
return Double.longBitsToDouble((Double.doubleToLongBits(x) << 1) >>> 1);
}
private static double estimate_root(int n, double k) {
// Extract the exponent from k.
long exp = (Double.doubleToLongBits(k) & 0x7ff0000000000000L);
// Format the exponent properly.
int D = (int) ((exp >> 52) - 1023);
// Calculate and return 2^(D/n).
return Double.longBitsToDouble((D / n + 1023L) << 52);
}
}
Just iterate until the update is less than say, 0.0001, if you want a precision of 4 decimals.
That is, set your epsilon to Math.pow(10, -n) if you want n digits of precision.
Let's recall what the error analysis of Newton's method says. Basically, it gives us an error for the nth iteration as a function of the error of the n-1 th iteration.
So, how can we tell if the error is less than k? We can't, unless we know the error at e(0). And if we knew the error at e(0), we would just use that to find the correct answer.
What you can do is say "e(0) <= m". You can then find n such that e(n) <= k for your desired k. However, this requires knowing the maximal value of f'' in your radius, which is (in general) just as hard a problem as finding the x intercept.
What you're checking is if the error changes by less than k, which is a perfectly acceptable way to do it. But it's not checking if the error is less than k. As Axel and others have noted, there are many other root-approximation algorithms, some of which will yield easier error analysis, and if you really want this, you should use one of those.
You have a bug in your code. Your pow() method's last line should read
return (y & 1) == 1 ? k : k * x;
rather than
return (y & 1) == 0 ? k : k * x;

Categories