Having trouble solving cubic equations in Java - java

I'm attempting to follow some psuedo code for solving cubic equations in Mathematics and Physics for Programmers, Chapter 3, as far as I can see I've followed it accurately, but I don't seem to be getting correct outputs.
For example: According to Wolfram Alpha 5x^3 + 4x^2 + 3x + 2 = 0 should give a root of x≈-0.72932, but I'm getting back -1.8580943294965526 from my script.
Can someone help me to work out what the hell I'm doing? I'm following the scripts to get a better understanding of maths and converting equations to code. But this is at the brink of my understanding so I'm finding it troublesome to debug. Coupled with the fact the book has no errata and many online reviews state the book has many errors, I'm struggling to see whether the issue is with my code, the books explanation or both.
The equation given in the book is:
Then if the discriminant > 0 then root has value of r+s:
if discriminant == 0 then there are two roots:
if discriminant < 0 you can find three roots as follows:
After finding t you can transform it to x by taking:
package com.oacc.maths;
public class SolveCubic {
public static double[] solveCubic(double a, double b, double c, double d) {
double[] result;
if (d != 1) {
a = a / d;
b = b / d;
c = c / d;
}
double p = b / 3 - a * a / 9;
double q = a * a * a / 27 - a * b / 6 + c / 2;
double D = p * p * p + q * q;
if (Double.compare(D, 0) >= 0) {
if (Double.compare(D, 0) == 0) {
double r = Math.cbrt(-q);
result = new double[2];
result[0] = 2 * r;
result[1] = -r;
} else {
double r = Math.cbrt(-q + Math.sqrt(D));
double s = Math.cbrt(-q - Math.sqrt(D));
result = new double[1];
result[0] = r + s;
}
} else {
double ang = Math.acos(-q / Math.sqrt(-p * p * p));
double r = 2 * Math.sqrt(-p);
result = new double[3];
for (int k = -1; k <= 1; k++) {
double theta = (ang - 2 * Math.PI * k) / 3;
result[k + 1] = r * Math.cos(theta);
}
}
for (int i = 0; i < result.length; i++) {
result[i] = result[i] - a / 3;
}
return result;
}
public static double[] solveCubic(double a, double b, double c) {
double d = 1;
return solveCubic(a, b, c, d);
}
public static void main(String args[]) {
double[] result = solveCubic(5, 4, 3, 2);
for (double aResult : result) {
System.out.println(aResult);
}
}
}
I also found this code example from the book site(n.b. this is not the psuedo code from the book): http://www.delmarlearning.com/companions/content/1435457331/files/index.asp?isbn=1435457331
on solveCubic(a,b,c,d)
--! ARGUMENTS:
a, b, c, d (all numbers). d is optional (default is 1)
--!
RETURNS: the list of solutions to dx^3+ax^2+bx+c=0
-- if d is defined then divide a, b and c by d
if not voidp(d)
then
if d=0 then return solveQuadratic(b,c,a)
set d to float(d)
set a to a/d
set b to b/d
set
c to c/d
else
set a to float(a)
set b to float(b)
set c to float(c)
end if
set p to b/3 - a*a/9
set q to a*a*a/27 - a*b/6 + c/2
set disc to p*p*p + q*q
if abs(disc)<0.001 then
set r to cuberoot(-q)
set ret to [2*r, -r]
else if disc>0 then
set r to cuberoot(-q+sqrt(disc))
set s to cuberoot(-q-sqrt(disc))
set ret to [r+s]
else
set ang to acos(-q/sqrt(-p*p*p))
set r to 2*sqrt(-p)
set ret to []
repeat with k=-1 to 1
set theta
to (ang - 2*pi*k)/3
ret.add(r*cos(theta))
end repeat
end if
set ret to ret-a/3 --NB: this adds the value to each
element
return ret
end

The error appears to be with the names of the parameters of your solveCubic method.
It seems your book is explaining how to solve the equation x3 + ax2 + bx + c = 0. You are calling your method thinking that the parameters a, b, c and d are for the equation ax3 + bx2 + cx + d = 0. However, it turns out that the body of your method is actually finding solutions to the equation dx3 + ax2 + bx + c = 0.
Aside from this naming error, the calculations appear to be correct. Try plugging your value ≈-1.858 into 2x3 + 5x2 + 4x + 3 if you don't believe me.
If you instead declare your solveCubic method as
public static double[] solveCubic(double d, double a, double b, double c) {
the parameters then correspond to the equation dx3 + ax2 + bx + c. You should then find that your method gives you the answer you expect.

Okay. So, first off the equations from the book seem to be referring to this idea: If you have an equation of the form:
Then by defining t as x - (a/3) you can transform this into an equation with no quadratic term, as verified by a bit of Mathematica:
Once you have no quadratic term, you can then apply the method given; let q be half the constant term, let p be one third the coefficient on the first power term, and define D (discriminant) as p*p*p - q*q.
All else then follows.
So why does your code not work? Because you've mislabeled the variables. a is the coefficient on x^2, not on x^3. If you call your method with the arguments (0.8, 0.6, 0.4, 1) or equivalently with (4, 3, 2, 5), you'll get the right answer.
(Or do as the other answer suggests and more around the variable names in the method declaration)

This works 100%. It has been tried and tested for all combinations.
public void solveCubicEquation(int A, int B, int C, int D) {
double a = (double) B / A;
double b = (double) C / A;
double c = (double) D / A;
System.out.println("Double values: ");
System.out.println(a + " " + b + " " + c);
double p = b - ((a * a) / 3.0);
double q = (2 * Math.pow(a, 3) / 27.0) - (a * b / 3.0) + c;
double delta = (Math.pow(q, 2) / 4) + (Math.pow(p, 3) / 27);
if (delta > 0.001) {
double mt1, mt2;
double t1 = (-q / 2.0) + Math.sqrt(delta);
double t2 = (-q / 2.0) - Math.sqrt(delta);
if (t1 < 0) {
mt1 = (-1) * (Math.pow(-t1, (double) 1 / 3));
} else {
mt1 = (Math.pow(t1, (double) 1 / 3));
}
if (t2 < 0) {
mt2 = (-1) * (Math.pow(-t2, (double) 1 / 3));
} else {
mt2 = (Math.pow(t2, (double) 1 / 3));
}
x1 = mt1 + mt2 - (a / 3.0);
} else if (delta < 0.001 && delta > -0.001) {
if (q < 0) {
x1 = 2 * Math.pow(-q / 2, (double) 1 / 3) - (a / 3);
x2 = -1 * Math.pow(-q / 2, (double) 1 / 3) - (a / 3);
} else {
x1 = -2 * Math.pow(q / 2, (double) 1 / 3) - (a / 3);
x2 = Math.pow(q / 2, (double) 1 / 3) - (a / 3);
}
} else {
System.out.println("here");
x1 = (2.0 / Math.sqrt(3)) * (Math.sqrt(-p) * Math.sin((1 / 3.0) * Math.asin(((3 * Math.sqrt(3) * q) / (2 * Math.pow(Math.pow(-p, (double) 1 / 2), 3)))))) - (a / 3.0);
x2 = (-2.0 / Math.sqrt(3)) * (Math.sqrt(-p) * Math.sin((1 / 3.0) * Math.asin(((3 * Math.sqrt(3) * q) / (2 * Math.pow(Math.pow(-p, (double) 1 / 2), 3)))) + (Math.PI / 3))) - (a / 3.0);
x3 = (2.0 / Math.sqrt(3)) * (Math.sqrt(-p) * Math.cos((1 / 3.0) * Math.asin(((3 * Math.sqrt(3) * q) / (2 * Math.pow(Math.pow(-p, (double) 1 / 2), 3)))) + (Math.PI / 6))) - (a / 3.0);
}
}
Note: will not work for imaginary values

Related

Adaptive Quadrature Algorithm - Recursive to Iterative

I would like to know if it is possible to make this algorithm iterative instead of recursive, and if its posible, could someone help me?.
public static double adaptiveQuadrature(double a, double b) {
double h = b - a;
double c = (a + b) / 2.0;
double d = (a + c) / 2.0;
double e = (b + c) / 2.0;
double Q1 = h / 6 * (f(a) + 4 * f(c) + f(b));
double Q2 = h / 12 * (f(a) + 4 * f(d) + 2 * f(c) + 4 * f(e) + f(b));
if (Math.abs(Q2 - Q1) <= EPSILON)
return Q2 + (Q2 - Q1) / 15;
else
return adaptiveQuadrature(a, c) + adaptiveQuadrature(c, b);
}
static double f(double x) {
return Math.exp( - x * x / 2) / Math.sqrt(2 * Math.PI);
}
Thank you so much for your help!
I don't think so. The size of the steps is depending on function evaluations made at the endpoints of the initial interval, then at the endpoints of subintervals. The pattern is not progressive and you can't organize a single loop that will "guess" the step ahead of time.
Of course you can derecursivate by means of an explicit stack, but that won't essentially change the nature of the process.

My code does exactly what it has to do, but i have no idea why

is supposed to calculate the coordinates of a projectile launched with respect to time (steps of 100ms), with a linear equation, and it outputs linear numbers, but if i plot this equation with CalcMe.com (math tool) it makes a parabolic plot
InVel = Double.parseDouble(jTextField1.getText());
g = Double.parseDouble(jTextField8.getText());
y = 1;
while(y >= -1) {
t += 100;
x = InVel * TimeUnit.MILLISECONDS.toSeconds(t) * Math.cos(45);
y = InVel * TimeUnit.MILLISECONDS.toSeconds(t) * Math.sin(45) - (1 / 2) * g * Math.pow(TimeUnit.MILLISECONDS.toSeconds(t), 2);
//System.out.print(Double.toString(x));
//System.out.printf(" ");
System.out.print(Double.toString(y));
System.out.printf("%n");
}
jTextField6.setText(Double.toString(x));
the code is in java
g is constant (9.8)
and invel is given by user so its constant too
g is the gravity and invel the initial velocity of the projectile
the equation is:x=invel*time*cos(45) and y=invel*time*sin(45)-(1/2)*g*t^2
anyone can help me?
Your milisecond to second value conversion method TimeUnit.MILLISECONDS.toSeconds(t) is the main fact. Its returning long value which one you are wanted double. Please take a look on below code. Probably its your answer. Just replace hard-coded value with your jTextField
public static void main(String[] args) {
double InVel = Double.parseDouble("10.555");
double g = Double.parseDouble("9.8");
double y = 1;
double x=0;
double t=0;
while(y >= -1) {
t += 100;
double timeInSeconds = (t / (double)1000) % (double)60;
x = InVel * timeInSeconds * Math.cos(45);
y = InVel * timeInSeconds * Math.sin(45) - ((double) 1 / (double) 2) * g * Math.pow(timeInSeconds, 2);
//System.out.print(Double.toString(x));
//System.out.printf(" ");
System.out.println("X = " + x + " Y = " + Double.toString(y));
System.out.printf("%n");
}
}

converting python to java float vs double

I need to convert the following python code to Java and remember from the past that handling decimal values must be done carefully otherwise the results will not be accurate.
My question is, can I use doubles for all non-interger values given doubles are more accurate that floats?
Here is my start of the conversion:
Python code
def degrees(rads):
return (rads/pi)*180
def radians(degrees):
return (degrees/180 * pi)
def fnday(y, m, d, h):
a = 367 * y - 7 * (y + (m + 9) // 12) // 4 + 275 * m // 9
a += d - 730530 + h / 24
return a
Java conversion
public double degress(double rads)
{
return (rads/PI)*180;
}
public double radians(double degrees)
{
return (degrees/180 * PI);
}
public double fnday(int y, int m, int d, int h)
{
double a = 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9;
a += d - 730530 + h / 24;
return a;
}
I know it may be a simple answer but I need to know the postion of the moon and sun for the app and do not want to rely on an api for this data. I simple want to put in the latitude and longitdue and get the sun and moon rise and set times.
Using a double for each variable would suffice; however, you have an issue that results from integer division:
double a = 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9;
If I were you, I'd change y, m, d, and h to all be doubles, so you retain the decimal places when dividing:
public double fnday(double y, double m, double d, double h) {
double a = 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9;
a += d - 730530 + h / 24;
return a;
}
If you need a really big precision, the best way is use,
java.lang.BigDecimal, that extends from java.math.Number.
You can even use your existing doubles if you need:
double d = 67.67;
BigDecimal bd = new BigDecimal(d);
But you will need to use the methods from the class like this:
public BigDecimal degress(BigDecimal rads)
{
BigDecimal pi = new BigDecimal(PI);
return (rads.divide(pi))*180;
}

How to calculate the angle between two vectors?

We are trying to get the cos value between v and u but we are getting results much higher than 1 or lesser than 0
Where :
vx = in.nextInt(); // x speed of your pod
vy = in.nextInt(); // y speed of your pod
int ux = nextCheckPointIdX - x;
int uy = nextCheckPointIdY - y;
Here is the formula :
double cos = (vx*ux + vy*uy) / ( Math.sqrt(Math.pow(vx, 2) + Math.pow(vy, 2)) + Math.sqrt(Math.pow(ux, 2) + Math.pow(uy, 2)) );
Do you find any errors in the previous line ?
The denominator was having the problem.
int num = (vx*ux + vy*uy);
double den = (Math.sqrt(Math.pow(vx, 2) + Math.pow(vy, 2)) * (Math.sqrt(Math.pow(ux, 2) + Math.pow(uy, 2))) );
double cos = num / den;
System.out.println(cos);
System.out.println(Math.acos(cos));

HSL to RGB Converter Not Working

I've been making an image editor in my free time and tried to use the HSL to RGB conversion formula here: HSL to RGB color conversion however I have come across an error.
Whenever I got to run my program the conversion does not work as it should, leaving the rgb with an unexpected grey colour. Here's some sample output data:
HSL: 0.0, 0.0, 1.0
RGB: 255.0, 255.0, 255.0
HSL: 214.0, 0.73, 0.5
RGB: 128.0, 128.0, 128.0
HSL: 214.0, 0.74, 0.5
RGB: 128.0, 128.0, 128.0
HSL: 214.0, 0.75, 0.5
RGB: 128.0, 128.0, 128.0
HSL: 214.0, 0.76, 0.5
RGB: 128.0, 128.0, 128.0
HSL: 214.0, 0.76, 0.5
RGB: 128.0, 128.0, 128.0
And below is my code. It's all written in Java.
public double[] hslToRgb(double h, double s, double l){
System.out.println("HSL: " + h + ", " + s + ", " + l);
double r = -1;
double b = -1;
double g = -1;
if(s == 0){
r = l;
b = l;
g = l;
}else{
double q = 1 < 0.5 ? l * (1 + s) : l + s - 1 * s;
double p = 2 * l - q;
r = hueToRgb(p, q, h + (1 / 3));
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - (1/ 3));
}
r = Math.round(r * 255);
b = Math.round(b * 255);
g = Math.round(g * 255);
System.out.println("RGB: " + r + ", " + g + ", " + b);
double[] rgb = {r, g, b};
return rgb;
}
private double hueToRgb(double p, double q, double t){
if(t < 0){
t++;
}
if(t > 1){
t--;
}
if(t < 1 / 6){
return p + (q - p) * 6 * t;
}
if(t < 1 / 2){
return q;
}
if(t < 2 / 3){
return p + (q - p) * ((2 / 3) - t) * 6;
}
return p;
}
Can anybody give me some insight as to what might be causing this? I feel like it's a minor error in my code but I can't find it anywhere.
Firstly, in the line double q = 1 < 0.5 ..., it's supposed to be the letter EL l, not the number 1 in two places.
double q = 1 < 0.5 ? l * (1 + s) : l + s - 1 * s;
^ ----- change from 1 to l ---- ^
Secondly, you have to be very careful about arithmetic which works differently in Java than JavaScript. When you have code like 1 / 3, since both are integers, the result will be an integer which means you get 0 rather than 0.3333.... In order to prevent using integer division, all of your divisions need to use at least one floating-point type:
if(t < 1.0 / 6){
^^^ change from 1 to 1.0
return p + (q - p) * 6 * t;
}
if(t < 1.0 / 2){
^^^ change from 1 to 1.0
return q;
}
if(t < 2.0 / 3){
^^^ change from 2 to 2.0
return p + (q - p) * ((2.0 / 3) - t) * 6;
^^^ change from 2 to 2.0
}
Also:
r = hueToRgb(p, q, h + (1.0 / 3));
^^^ change from 1 to 1.0
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - (1.0 / 3));
^^^ change from 1 to 1.0
Finally, in the code you copied from, the values for h, s, and l are all supposed to be between 0 and 1. So an H of 214 is not valid in your examples - you need to divide it by 360 first.
Here is a working code sample with the changes applied: http://ideone.com/QbXyYi
Input: 240.0 / 360.0, 1.0, 0.5
Output: [0, 0, 255.0]

Categories