how to assign a complex number to Set<Integer> z? - java

How to make the method roots check imaginary roots and real one then return their values?
package warmup;
import java.util.HashSet;
import java.util.Set;
public class Quadratic {
/**
* Find the integer roots of a quadratic equation, ax^2 + bx + c = 0.
* #param a coefficient of x^2
* #param b coefficient of x
* #param c constant term. Requires that a, b, and c are not ALL zero.
* #return all integers x such that ax^2 + bx + c = 0.
*/
public static Set<Integer> roots(int a, int b, int c) {
Set<Integer> z = new HashSet<>();
int temp1 = (int)(Math.sqrt(b*b - 4*a*c));
if(a !=0){
if(temp1 >= 0){
Integer x1 = (int) ((-b + temp1) / (2*a));
Integer x2 = (int) ((-b - temp1) / (2*a));
z.add(x1);
z.add(x2);
} else if (temp1 < 0){
Integer x1 = (int) ((-b + temp1) / (2*a));
Integer x2 = (int) ((-b - temp1) / (2*a));
z.add(x1);
z.add(x2);
}
}else{
System.out.println("Error: division by zero.");
}
return z;
}
/**
* Main function of program.
* #param args command-line arguments
*/
public static void main(String[] args) {
System.out.println("For the equation x^2 - 4x + 3 = 0, the possible solutions are:");
Set<Integer> result = roots(1, -4, 3);
System.out.println(result);
}

trying to assign a negative square root number value to java is not allowed in JDK.
what you can do is, you can create a complex number class of your own and do your own operations there. Here is the example which i found online:
http://introcs.cs.princeton.edu/java/97data/Complex.java.html
I also looked at SO for similar questions like yours and i got this link
Hope this helps

Related

efficient algorithm for Pythagorean Triples in java

So I try to make a program using java.
its input is integers, the integers are considered as the sum of 3 integers a, b and c (a^2 + b^2 = c^2), its output is c^2. To do this, I expand the equation combine a^2 + b^2 - c^2 = 0 and c = sum - a - b, get Math.pow(sum, 2) - 2 * sum * (a + b) + 2 * a * b. Then I get a + b <= sum*2/3 then I substitute all the combination of a, b into the equation to see when it is zero.
Here is my code:
/** Pythagorean Triples
* test case for small numbers
* Tony
*/
import java.util.*;
public class Solution54 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
for (int i = 0; i < times; i++) {
/* prompt the sum and get the equation:
* Math.pow(sum, 2) - 24 * (a + b) + 2a*b = 0;
* we consider b >= a;
*/
double sum = sc.nextDouble();
double ablimits = Math.floor(sum / 3 * 2); // a + b <= ablimits
double alimits = Math.floor(ablimits / 2); // a <= alimits
//System.out.println("another round");
//System.out.print(alimits + " " + blimits);
A: for (double a = 1; a <= alimits; a++) {
B: for (double b = a; b <= sum - a; b++) {
double result = Math.pow((sum-a-b),2)-a*a-b*b;
//System.out.print("when a is " + a + " " + "when b is " + b + ":" + result + ";");
if (Math.pow(sum, 2) - 2 * sum * (a + b) + 2 * a * b == 0) {
double answer = a*a + b*b;
int output = (int)answer;
System.out.print(output + " ");
break A;
}
}
}
}
}
}
When I input 1 12 , it gives 25(because a,b,c=3,4,5; c^2 = 25), but it can't handle big inputs like 14808286 because my algorithm is not efficient enough. What is the efficient way to do this? Plz!
Let me preface this by saying I don't have intimate knowledge of Pythagorean triples or the math behind them. I just thought this was an interesting problem, so I gave it a stab.
I believe the key to this problem is knowing what you're looking for as you scan through possible values of a. Given
a + b + c = sum
and
a^2 + b^2 = c^2
you'll find that
b = (sum / 2) * (1 - (a / (sum - a)))
= (sum / 2) - ((a * sum) / (2 * (sum - a)))
You know that b must be a whole number. An interesting property of Pythagorean triples is that their sums are always even. That means that
(sum / 2) % 1 = 0
So all we really need to check to make sure b is valid (i.e. a whole number) is that
((a * sum) / (2 * (sum - a))) % 1 = 0
or, put more simply,
(a * sum) % (sum - a) = 0
Some other key points that simplify this problem, at least as you've stated it:
Once you have a, b can be computed using the third equation in this answer.
Once you have a and b, c follows easily from either of the Pythagorean triple equations.
You only need to print c^2 as your output. Once this is done you can break.
The code ends up being pretty simple:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Get the sum from System.in.
int sum = sc.nextInt();
// If the given sum is odd, return immediately.
// No Pythagorean triple will have an odd sum.
if ((sum ^ 1) == 1) {
return;
}
// Try all values of a within the expected bounds.
int aBound = sum / 2;
for (int a = 1; a < aBound; a++) {
// Check whether b would be a whole number with this value of a.
if ((a * sum) % (a - sum) == 0) {
int b = (sum * (2 * a - sum)) / (2 * a - 2 * sum);
int c = sum - a - b;
System.out.println((int)Math.pow(c, 2));
break;
}
}
}
It's worth noting that because I lack deep mathematical understanding of Pythagorean triples, there's very likely some further optimization that can be done in deciding which values of a actually need to be checked. I imagine there's some mathematical criteria for that.
I hope this helps!

Why is the output (Nan,Nan)? [duplicate]

This question already has answers here:
What does the ^ operator do in Java?
(19 answers)
Closed 7 years ago.
So I'm new to Java and I have an assignment to do for class, but I'm stuck. The class is supposed to find the intersection of two lines using the quadratic equation. I was told to have specific inputs for class, so d = 5, f = -3, g = 2, m = 1 and b = 3 and the two intersections are supposed to be (1,4) and (-.20,2.8). The problem I'm running into is that the output returns (NaN,NaN) and (NaN,NaN) instead of the right answer. Is there anything wrong with my code that is making me get this answer?
public class Intersect{
public static void main(String args[]){
//prompt user for parabola vars d f g
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
// y = dx^2 + fx + g
//promt user for line vars m b
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
// y = mx + b
//compute intersection
// dx^2 + fx + g = mx + b
// x^2 * (d) + x * (f-m) + (g-b) = 0
int a = d;
int z = (f-m);
int c = (g-b);
double x1 = -z + (Math.sqrt (z^2 - 4 * a * c) / (2 * a));
double x2 = -z - (Math.sqrt (z^2 - 4 * a * c) / (2 * a));
double y1 = m * x1 + b;
double y2 = m * x2 - b;
//output each intersection on its own line, System.out.println() is ok for this answer submission
System.out.println("The intersection(s) are:");
System.out.println("(" + x1 + "," + y1 + ")");
System.out.println("(" + x2 + "," + y2 + ")");
}
}
^ is the xor operator in java and not the exponentiation operator. Therefore, the expresson z ^ 2 - 4 * a * c computes to something negative.
From the input you provide, z = -4, a = 5, c = -1. The expression translates to -4 ^ 2 - 4 * 5 * -1. Note that * and + have a higher precedence than ^, i.e. the order of evaluation is (-4 ^ (2 - ((4 * 5) * -1))) = -22.
Then you're trying to find the square root of -22, which, according to Math.sqrt(), is NaN.
Use Math.pow(z, 2), or simply use z * z instead:
Math.sqrt(z * z - 4 * a * c); // Note: This time operator precedence works,
// But you should use parentheses wherever
// the expression seems ambiguous.
First of all ^ is not an exponentiation operator, what causes Nan is the fact that you pass in a negative argument to Math.sqrt.
From java reference ( http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html ):
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.
Its your order of operations that is causing you to get NaN results.
Try this(added variables for convenience):
int a = d;
int z = f - m;
int negZ = -z;
int c = g - b;
double sq = Math.sqrt((z * z) - (4 * a * c));
double a2 = 2 * a;
double x1 = (negZ + sq) / a2;
double x2 = (negZ - sq) / a2;
double y1 = (m * x1) + b;
double y2 = (m * x2) - b;

Java - Numerical Integration of a complex function - Zeta function, Abel-Plana formula

(Note: I found a partial solution. I have pasted the test results at the end)
I am looking to numerically integrate an approximation of the zeta function. This is done through what is known as the Abel-Plana formula. The Abel-Plana formula can be used to numerically evaluate Zeta(s) for s = a + i*b.
I first wrote a program to calculate Zeta(s) for s in real. It seems to work,
/**************************************************************************
**
** Abel-Plana Formula for the Zeta Function
**
**************************************************************************
** Axion004
** 08/16/2015
**
** This program computes the value for Zeta(s) using a definite integral
** approximation through the Abel-Plana formula. The Abel-Plana formula
** can be shown to approximate the value for Zeta(s) through a definite
** integral. The integral approximation is handled through the Composite
** Simpson's Rule known as Adaptive Quadrature.
**************************************************************************/
import java.util.*;
import java.math.*;
public class AbelMain2 {
public static void main(String[] args) {
AbelMain();
}
public static void AbelMain() {
double s = 0;
double start, stop, totalTime;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the value of s inside the Riemann Zeta " +
"Function: ");
try {
s = scan.nextDouble();
}
catch (Exception e) {
System.out.println("Please enter a valid number for s.");
}
start = System.currentTimeMillis();
System.out.println("The value for Zeta(s) is " + AbelPlana(s));
stop = System.currentTimeMillis();
totalTime = (double) (stop-start) / 1000.0;
System.out.println("Total time taken is " + totalTime + " seconds.");
}
// The definite integral for Zeta(s) in the Abel Plana formula.
// Numerator = Sin(s * arctan(t))
// Denominator = (1 + t^2)^(s/2) * (e^(pi*t) + 1)
public static double function(double x, double s) {
double num = Math.sin(s * Math.atan(x));
double den = Math.pow((1.0 + Math.pow(x, 2.0)), s / 2.0) *
(Math.pow(Math.E, Math.PI * x) + 1.0);
return num / den;
}
// Adaptive quadrature - See http://www.mathworks.com/moler/quad.pdf
// Used to approximate values for definite integrals
// Parameters - a is the start of the integral, b is the end of the
// integral, s is the double value used to evaulate Zeta(s).
public static double adaptiveQuad(double a, double b, double s) {
double EPSILON = 1E-6;
double step = b - a;
double c = (a + b) / 2.0;
double d = (a + c) / 2.0;
double e = (b + c) / 2.0;
double S1 = step / 6.0 * (function(a, s) + 4*function(c, s) +
function(b, s));
double S2 = step / 12.0 * (function(a, s) + 4*function(d, s) +
2*function(c, s) + 4*function(e, s) + function(b, s));
if (Math.abs(S2 - S1) <= EPSILON)
return S2 + (S2 - S1) / 15.0;
else
return adaptiveQuad(a, c, s) + adaptiveQuad(c, b, s);
}
// Returns an approximate sum of Zeta(s) through an integral aproximation
// by Adaptive Quadrature
public static double AbelPlana(double s) {
double C1 = Math.pow(2.0, s - 1.0) / (s - 1.0);
double C2 = Math.pow(2.0, s);
return C1 - C2 *adaptiveQuad(0, 10, s);
}
}
I then tried to extend this program to s in complex. It appears that the program doesn't work because I am trying to numerically evaluate a complex function through quadrature. The quadrature method that I wrote is only applicable to real-value functions as shown in Adaptive Quadrature. The work around I used is rather strange although it seems to work.
Here is what I wrote for the numerical approximation. I had to use a helper class in order to calculate complex numbers in Java.
/**************************************************************************
**
** Abel-Plana Formula for the Zeta Function
**
**************************************************************************
** Axion004
** 08/16/2015
**
** This program computes the value for Zeta(s) using a definite integral
** approximation through the Abel-Plana formula. The Abel-Plana formula
** can be shown to approximate the value for Zeta(s) through a definite
** integral. The integral approximation is handled through the Composite
** Simpson's Rule known as Adaptive Quadrature.
**************************************************************************/
import java.util.*;
import java.math.*;
public class AbelMain extends Complex {
public static void main(String[] args) {
AbelMain();
}
public static void AbelMain() {
double re = 0;
double im = 0;
double start, stop, totalTime;
Scanner scan = new Scanner(System.in);
System.out.println("Calculation of the Riemann Zeta " +
"Function in the form Zeta(s) = a + ib.");
System.out.println();
System.out.print("Enter the value of [a] inside the Riemann Zeta " +
"Function: ");
try {
re = scan.nextDouble();
}
catch (Exception e) {
System.out.println("Please enter a valid number for a.");
}
System.out.print("Enter the value of [b] inside the Riemann Zeta " +
"Function: ");
try {
im = scan.nextDouble();
}
catch (Exception e) {
System.out.println("Please enter a valid number for b.");
}
start = System.currentTimeMillis();
Complex z = new Complex(re, im);
if ( re == 1 && im == 0)
System.out.println("Zeta(s) is undefined for Zeta(1 + 0*i).");
else
System.out.println("The value for Zeta(s) is " + AbelPlana(z));
stop = System.currentTimeMillis();
totalTime = (double) (stop-start) / 1000.0;
System.out.println("Total time taken is " + totalTime + " seconds.");
}
// The definite integral for Zeta(s) in the Abel Plana formula.
// Numerator = Sin(s * arctan(t))
// Denominator = (1 + t^2)^(s/2) * (e^(pi*t) + 1)
public static Complex f(double t, Complex z) {
Complex num = (z.multiply(Math.atan(t))).sin();
Complex D1 = new Complex(1 + t*t, 0).pow(z.divide(2.0));
double D2 = Math.pow(Math.E, Math.PI * t) + 1.0;
Complex den = D1.multiply(D2);
return num.divide(den);
}
// Adaptive quadrature - See http://www.mathworks.com/moler/quad.pdf
// Used to approximate values for definite integrals
// Parameters - a is the start of the integral, b is the end of the
// integral, s is the double value used to evaulate Zeta(s).
public static Complex adaptiveQuad(double a, double b, Complex s) {
double EPSILON = 1E-6;
double step = b - a;
double c = (a + b) / 2.0;
double d = (a + c) / 2.0;
double e = (b + c) / 2.0;
Complex S1 = (f(a, s).add(f(c, s).multiply(4)).add(f(b, s))).
multiply(step / 6.0);
Complex S2 = (f(a, s).add(f(d, s).multiply(4)).add(f(c, s).multiply(2))
.add(f(e, s).multiply(4)).add(f(b, s))).multiply(step / 12.0);
Complex result = (S2.minus(S1)).divide(15.0);
if(S2.minus(S1).mod() <= EPSILON)
return S2.add(result);
else
return adaptiveQuad(a, c, s).add(adaptiveQuad(c, b, s));
}
// Returns an approximate sum of Zeta(s) through an integral aproximation
// by Adaptive Quadrature
public static Complex AbelPlana(Complex z) {
Complex two = new Complex(2.0, 0.0);
Complex C1 = two.pow(z.minus(1.0)).divide(z.minus(1.0));
Complex C2 = two.pow(z);
Complex mult = C2.multiply(adaptiveQuad(0, 10, z));
if ( z.re < 0 && z.re % 2 == 0 && z.im == 0)
return new Complex(0.0, 0.0);
else
return C1.minus(mult);
}
public AbelMain(double re, double im) {
super(re, im);
}
}
The second class for Complex numbers.
/**************************************************************************
**
** Complex Numbers
**
**************************************************************************
** Axion004
** 08/20/2015
**
** This class is necessary as a helper class for the calculation of
** imaginary numbers. The calculation of Zeta(s) inside AbelMain is in
** the form of z = a + i*b.
**************************************************************************/
public class Complex extends Object{
public double re;
public double im;
/**
Constructor for the complex number z = a + i*b
#param re Real part
#param im Imaginary part
*/
public Complex (double re, double im) {
this.re = re;
this.im = im;
}
/**
Real part of the Complex number
#return Re[z] where z = a + i*b.
*/
public double real() {
return re;
}
/**
Imaginary part of the Complex number
#return Im[z] where z = a + i*b.
*/
public double imag() {
return im;
}
/**
Complex conjugate of the Complex number
in which the conjugate of z is z-bar.
#return z-bar where z = a + i*b and z-bar = a - i*b
*/
public Complex conjugate() {
return new Complex(re, -im);
}
/**
Addition of two Complex numbers (z is unchanged).
<br>(a+i*b) + (c+i*d) = (a+c) + i*(b+d)
#param t is the number to add.
#return z+t where z = a+i*b and t = c+i*d
*/
public Complex add(Complex t) {
return new Complex(re + t.real(), im + t.imag());
}
/**
Addition of Complex number and a double.
#param d is the number to add.
#return z+d where z = a+i*b and d = double
*/
public Complex add(double d){
return new Complex(this.re + d, this.im);
}
/**
Subtraction of two Complex numbers (z is unchanged).
<br>(a+i*b) - (c+i*d) = (a-c) + i*(b-d)
#param t is the number to subtract.
#return z-t where z = a+i*b and t = c+i*d
*/
public Complex minus(Complex t) {
return new Complex(re - t.real(), im - t.imag());
}
/**
Subtraction of Complex number and a double.
#param d is the number to subtract.
#return z-d where z = a+i*b and d = double
*/
public Complex minus(double d){
return new Complex(this.re - d, this.im);
}
/**
Complex multiplication (z is unchanged).
<br> (a+i*b) * (c+i*d) = (a*c)+ i(b*c) + i(a*d) - (b*d)
#param t is the number to multiply by.
#return z*t where z = a+i*b and t = c+i*d
*/
public Complex multiply(Complex t) {
return new Complex(re * t.real() - im * t.imag(), re *
t.imag() + im * t.real());
}
/**
Complex multiplication by a double.
#param d is the double to multiply by.
#return z*d where z = a+i*b and d = double
*/
public Complex multiply(double d){
return new Complex(this.re * d,this.im * d);}
/**
Modulus of a Complex number or the distance from the origin in
* the polar coordinate plane.
#return |z| where z = a + i*b.
*/
public double mod() {
if ( re != 0.0 || im != 0.0)
return Math.sqrt(re*re + im*im);
else
return 0.0;
}
/**
* Modulus of a Complex number squared
* #param z = a + i*b
* #return |z|^2 where z = a + i*b
*/
public double abs(Complex z) {
return Math.sqrt(Math.pow(re*re, 2) + Math.pow(im*im, 2));
}
/**
Division of Complex numbers (doesn't change this Complex number).
<br>(a+i*b) / (c+i*d) = (a+i*b)*(c-i*d) / (c+i*d)*(c-i*d) =
* (a*c+b*d) + i*(b*c-a*d) / (c^2-d^2)
#param t is the number to divide by
#return new Complex number z/t where z = a+i*b
*/
public Complex divide (Complex t) {
double denom = Math.pow(t.mod(), 2); // Square the modulus
return new Complex((re * t.real() + im * t.imag()) / denom,
(im * t.real() - re * t.imag()) / denom);
}
/**
Division of Complex number by a double.
#param d is the double to divide
#return new Complex number z/d where z = a+i*b
*/
public Complex divide(double d){
return new Complex(this.re / d, this.im / d);
}
/**
Exponential of a complex number (z is unchanged).
<br> e^(a+i*b) = e^a * e^(i*b) = e^a * (cos(b) + i*sin(b))
#return exp(z) where z = a+i*b
*/
public Complex exp () {
return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) *
Math.sin(im));
}
/**
The Argument of a Complex number or the angle in radians
with respect to polar coordinates.
<br> Tan(theta) = b / a, theta = Arctan(b / a)
<br> a is the real part on the horizontal axis
<br> b is the imaginary part of the vertical axis
#return arg(z) where z = a+i*b.
*/
public double arg() {
return Math.atan2(im, re);
}
/**
The log or principal branch of a Complex number (z is unchanged).
<br> Log(a+i*b) = ln|a+i*b| + i*Arg(z) = ln(sqrt(a^2+b^2))
* + i*Arg(z) = ln (mod(z)) + i*Arctan(b/a)
#return log(z) where z = a+i*b
*/
public Complex log() {
return new Complex(Math.log(this.mod()), this.arg());
}
/**
The square root of a Complex number (z is unchanged).
Returns the principal branch of the square root.
<br> z = e^(i*theta) = r*cos(theta) + i*r*sin(theta)
<br> r = sqrt(a^2+b^2)
<br> cos(theta) = a / r, sin(theta) = b / r
<br> By De Moivre's Theorem, sqrt(z) = sqrt(a+i*b) =
* e^(i*theta / 2) = r(cos(theta/2) + i*sin(theta/2))
#return sqrt(z) where z = a+i*b
*/
public Complex sqrt() {
double r = this.mod();
double halfTheta = this.arg() / 2;
return new Complex(Math.sqrt(r) * Math.cos(halfTheta), Math.sqrt(r) *
Math.sin(halfTheta));
}
/**
The real cosh function for Complex numbers.
<br> cosh(theta) = (e^(theta) + e^(-theta)) / 2
#return cosh(theta)
*/
private double cosh(double theta) {
return (Math.exp(theta) + Math.exp(-theta)) / 2;
}
/**
The real sinh function for Complex numbers.
<br> sinh(theta) = (e^(theta) - e^(-theta)) / 2
#return sinh(theta)
*/
private double sinh(double theta) {
return (Math.exp(theta) - Math.exp(-theta)) / 2;
}
/**
The sin function for the Complex number (z is unchanged).
<br> sin(a+i*b) = cosh(b)*sin(a) + i*(sinh(b)*cos(a))
#return sin(z) where z = a+i*b
*/
public Complex sin() {
return new Complex(cosh(im) * Math.sin(re), sinh(im)*
Math.cos(re));
}
/**
The cos function for the Complex number (z is unchanged).
<br> cos(a +i*b) = cosh(b)*cos(a) + i*(-sinh(b)*sin(a))
#return cos(z) where z = a+i*b
*/
public Complex cos() {
return new Complex(cosh(im) * Math.cos(re), -sinh(im) *
Math.sin(re));
}
/**
The hyperbolic sin of the Complex number (z is unchanged).
<br> sinh(a+i*b) = sinh(a)*cos(b) + i*(cosh(a)*sin(b))
#return sinh(z) where z = a+i*b
*/
public Complex sinh() {
return new Complex(sinh(re) * Math.cos(im), cosh(re) *
Math.sin(im));
}
/**
The hyperbolic cosine of the Complex number (z is unchanged).
<br> cosh(a+i*b) = cosh(a)*cos(b) + i*(sinh(a)*sin(b))
#return cosh(z) where z = a+i*b
*/
public Complex cosh() {
return new Complex(cosh(re) *Math.cos(im), sinh(re) *
Math.sin(im));
}
/**
The tan of the Complex number (z is unchanged).
<br> tan (a+i*b) = sin(a+i*b) / cos(a+i*b)
#return tan(z) where z = a+i*b
*/
public Complex tan() {
return (this.sin()).divide(this.cos());
}
/**
The arctan of the Complex number (z is unchanged).
<br> tan^(-1)(a+i*b) = 1/2 i*(log(1-i*(a+b*i))-log(1+i*(a+b*i))) =
<br> -1/2 i*(log(i*a - b+1)-log(-i*a + b+1))
#return arctan(z) where z = a+i*b
*/
public Complex atan(){
Complex ima = new Complex(0.0,-1.0); //multiply by negative i
Complex num = new Complex(this.re,this.im-1.0);
Complex den = new Complex(-this.re,-this.im-1.0);
Complex two = new Complex(2.0, 0.0); // divide by 2
return ima.multiply(num.divide(den).log()).divide(two);}
/**
* The Math.pow equivalent of two Complex numbers.
* #param z - the complex base in the form z = a + i*b
* #return z^y where z = a + i*b and y = c + i*d
*/
public Complex pow(Complex z){
Complex a = z.multiply(this.log());
return a.exp();
}
/**
* The Math.pow equivalent of a Complex number to the power
* of a double.
* #param d - the double to be taken as the power.
* #return z^d where z = a + i*b and d = double
*/
public Complex pow(double d){
Complex a=(this.log()).multiply(d);
return a.exp();
}
/**
Override the .toString() method to generate complex numbers, the
* string representation is now a literal Complex number.
#return a+i*b, a-i*b, a, or i*b as desired.
*/
public String toString() {
if (re != 0.0 && im > 0.0) {
return re + " + " + im +"i";
}
if (re !=0.0 && im < 0.0) {
return re + " - "+ (-im) + "i";
}
if (im == 0.0) {
return String.valueOf(re);
}
if (re == 0.0) {
return im + "i";
}
return re + " + i*" + im;
}
public static void main(String[] args) {
Complex s = new Complex(2.0, 3.0);
Complex y = new Complex(3.0, 4.0);
Complex d = new Complex(4.0, 2.0);
Complex x = new Complex(1.0, 0.0);
System.out.println(s.atan());
System.out.println(s.divide(d));
System.out.println(s.im);
System.out.println(s.pow(y));
System.out.println(s.pow(2.0));
}
}
I did some preliminary testing and it seems that both the public static Complex f and public static Complex AbelPlana methods work fine. I checked these calculations against Mathematica. The method for
public static Complex adaptiveQuad(double a, double b, Complex z)
also works (for low values).
Calculation of the Riemann Zeta Function in the form Zeta(s) = a + ib.
Enter the value of [a] inside the Riemann Zeta Function: -12
Enter the value of [b] inside the Riemann Zeta Function: 1.2
The value for Zeta(s) is 0.0900630360334386 + 0.08241454022912213*i
Total time taken is 0.014 seconds.
Enter the value of [a] inside the Riemann Zeta Function: 0.3
Enter the value of [b] inside the Riemann Zeta Function: -2.1
The value for Zeta(s) is 0.4003421605328948 + 0.2570024810252463*i
Total time taken is 0.005 seconds.
Enter the value of [a] inside the Riemann Zeta Function: 1
Enter the value of [b] inside the Riemann Zeta Function: 2
The value for Zeta(s) is 0.598165521081844 - 0.35185471257583556*i
Total time taken is 0.005 seconds.
Enter the value of [a] inside the Riemann Zeta Function: 0.5
Enter the value of [b] inside the Riemann Zeta Function: 10
The value for Zeta(s) is 1.5448963436469043 - 0.1153378574814412*i
Total time taken is 0.014 seconds.
Something is clearly wrong with larger values.
Enter the value of [a] inside the Riemann Zeta Function: 24
Enter the value of [b] inside the Riemann Zeta Function: -8
The value for Zeta(s) is 164561.70457820524 + 302628.94685036544*i
Total time taken is 0.003 seconds.
I scanned the internet and couldn't find a method for numerical integration of complex functions. The integral for the approximation is shown in here. It doesn't seem like I can use this relationship in the program (it needs to calculate the Zeta(z) for z = a+i*b anyhow).
I searched and found this, and this. Do I need to reference the Apache Commons Math library to numerically integrate a complex function? I would prefer to write a method to do this myself. My current knowledge doesn't seem to be sufficient, all of the numerical integration methods that I know directly approximate real-valued functions.
I will review why my method fails for large values...

Why won't this quadratic equation return negative numbers?

This quadratic equation will not return negative numbers in the string that I've determined it to return.
Here's the equation:
public class QuadraticEquation {
String final0;
public String calculate(int a, int b, int c) {
double done1 = ((-1 * b) + Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
double done2 = ((-1 * b) - Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
final0 = "x = " + (done1) + " or x = " + (done2);
return final0;
}
}
imagine an equation with a, b, and c values like -3, 13, and -4. The returning value of this would be -0.3(repeating) and -4. But this equation only returns positives, so in this case it would return 0.3(repeating) and 4. Why is this, and what can I do to fix it?
Note: I do believe that this is a Java error and not a math error. If it is a math error, let me know in the comments and I will promptly put it in the proper forums. Thanks.
public static void main(String[] args) {
String final0 = calculate(-3, 13, -4);
System.out.println(final0);
}
public static String calculate(int a, int b, int c) {
String final0 ;
int i = -1 * b; // -1 * 13 = -13
System.out.println(i);
int j = 4 * a * c; // 4 * -3 * -4 = 4 * 12 = 48
System.out.println(j);
double sqrt = Math.sqrt((b * b) - j); // sqrt ((13 * 13) - 48) = sqrt(169 - 48) = sqrt(121) = 11
System.out.println(sqrt);
double d = i + sqrt; // -13 + 11 = -2
System.out.println(d);
int k = 2 * a; // 2* -3 = -6
System.out.println(k);
double done1 = d / k; // -2 / -6 = 1/3 = 0.3333333333
System.out.println(done1);
double done2 = (i - sqrt) / k;
final0 = "x = " + (done1) + " or x = " + (done2);
return final0;
}
If you decompose your method to more local variables, you will see that math in java works correctly.
I would have thought
-3*x^2 + 13 *x + -4 = -3 * (x - 0.33333) * (x - 4) = 0
so two positive answers is correct.
Try instead
1 * x^2 + 0 * x -1 = (x - 1) * (x + 1) = 0
i.e. x = -1 or +1
Here is how I would write it.
public static String calculate(int a, int b, int c) {
double sqrt = Math.sqrt((b * b) - (4 * a * c));
double done1 = (-b + sqrt) / (2 * a);
double done2 = (-b - sqrt) / (2 * a);
return "x = " + (done1) + " or x = " + (done2);
}
The code is working correctly with your input. If you changed b to be -13 for example, you would get
x = -4.0 or x = -0.3333333333333333
Math.sqrt will always return a positive number ignoring complex numbers. But that is somewhat besides the point.

Why Quadratic equation's root result is NaN ? (Java)

Why write out
The roots are NaN and NaN in console?
I've read about NaN, but I don't find the right solution how can I repair the mistakes...
I've tried casting to double the discriminant and the roots but doesn't work.
Can somebody help me, where and what I need to rewrite?
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Pattern newlineOrSpace = Pattern.compile(System
.getProperty("line.separator")
+ "|\\s");
sc.useDelimiter(newlineOrSpace);
System.out.print("Enter a, b, c: ");
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
// System.out.format("a = %f, b = %f, c = %f", a, b, c);
double root1;
double root2;
double discriminant;
discriminant = Math.sqrt(b * b - 4 * a * c);
if (discriminant > 0) {
System.out.println("There are no real roots ");
} else {
root1 = (-b + discriminant) / (2 * a);
root2 = (-b - discriminant) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
Math.sqrt(x) returns NaN when x is negative, which then propagates through the rest of your code. You'll want to test for negative numbers before taking the square root:
discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
System.out.println("There are no real roots ");
} else {
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
Firstly, let's get rid of user input as a cause for this - it's much easier if the short but complete program contains all the data we need:
public class Test {
public static void main(String args[]) {
showRoots(2.0, 10.0, 2.0);
showRoots(10.0, 1.0, 1.0);
}
private static void showRoots(double a, double b, double c) {
double discriminant = Math.sqrt(b * b - 4 * a * c);
if (discriminant > 0) {
System.out.println("There are no real roots ");
} else {
double root1 = (-b + discriminant) / (2 * a);
double root2 = (-b - discriminant) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
}
}
This shows two cases - one where there really are roots - but the program claims there aren't - and one where there really aren't real roots, but the program prints them out as NaN. When you take the square root of a negative number, the result is NaN, which is why that's being displayed.
So, the problem is how you're dealing with the discriminant. There are real roots if b2 - 4ac is non-negative - but you've already taken the square root at that point and reversed the nature of the condition.
So, it should be:
private static void showRoots(double a, double b, double c) {
double discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
System.out.println("There are no real roots ");
} else {
double discriminantRoot = Math.sqrt(discriminant);
double root1 = (-b + discriminantRoot) / (2 * a);
double root2 = (-b - discriminantRoot) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
}
Lessons to learn:
When you want to demonstrate a problem, it helps to keep it minimal; using hard-coded values is a good way of doing this
Be careful about the order of operations - in this case, you were trying to judge something using the wrong value because you'd taken the square root too early
Be careful with conditions and whether or not you're getting them the right way round
EDIT: As noted in comments, there are various special cases to consider too, including when a is 0 which would otherwise lead to a division by 0 issue.
Do
double discriminant = b * b - 4 * a * c;
if (discriminant >= 0) {
discriminant = Math.sqrt(discriminant);
root1 = (-b + discriminant) / (2 * a);
root2 = (-b - discriminant) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
else {
System.out.println("There are no real roots ");
}
You get that when your discriminant is negative. Like for a=1,b=2,c=3. Delta = 2*2 -4*1*3 = 4 - 12 = -8
Java can't calculate square root of negative number, it doesn't know about imaginary number i.

Categories

Resources