import java.util.Scanner;
/**
* Calculates the amount of fuel needed.
*
* #param distance The distance of the trip.
* #param milesPerLiter Total distance that could be achieved with 1 liter of fuel.
* #return Total fuel needed.
*/
public static double calcFuelNeeded(double distance, double milesPerLiter) {
double fuelNeeded = distance / milesPerLiter;
return (fuelNeeded);
//FILL IN THE BODY
}
/**
* Calculates the total number of gallons needed.
*
* #param fuelNeeded Total fuel needed.
* #param litersPerGallon The volume of each gallon.
* #return Total number of gallons needed.
*/
public static int calcGallonsFuelNeeded(double fuelNeeded, double litersPerGallon) {
double gallonsFuel = Math.ceil(fuelNeeded / litersPerGallon);
return (int) gallonsFuel;//FILL IN THE BODY
}
/**
* Calculates the total cost needed.
*
* #param gallonsFuel Total number of gallons needed.
* #param costPerGallon The cost of each gallon.
* #return The total cost of the trip.
*/
public static double calcCostNeeded(int gallonsFuel, double costPerGallon) {
double costNeeded = gallonsFuel * costPerGallon;
return costNeeded;//FILL IN THE BODY
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the distance to be covered (miles):");
double distance;
distance = scnr.nextDouble();
double milesPerLiter = 13.7;
double litersPerGallon = 3.785;
double costPerGallon = 2.629;
scnr.close();
System.out.println("Fuel Needed: " + calcFuelNeeded(distance, milesPerLiter) + " liter(s)");
System.out.println("Gallons needed: " + calcGallonsFuelNeeded( calcFuelNeeded(distance, milesPerLiter), litersPerGallon) + " gallon(s)");
System.out.println("Cost needed: " +calcCostNeeded( calcGallonsFuelNeeded( calcFuelNeeded(distance, milesPerLiter), litersPerGallon), costPerGallon) + " $" );
}
Could someone please tell me what is wrong with this program, since there is always error appear like
You need to put the contents within a class
Example:
package com.example.demo;
import java.util.Scanner;
public class Demo {
/**
* Calculates the amount of fuel needed. * * #param distance The distance of the trip. * #param milesPerLiter Total distance that could be achieved with 1 liter of fuel. * #return Total fuel needed. */ public static double calcFuelNeeded(double distance, double milesPerLiter) {
double fuelNeeded = distance / milesPerLiter;
return (fuelNeeded);
//FILL IN THE BODY
}
/**
* Calculates the total number of gallons needed. * * #param fuelNeeded Total fuel needed. * #param litersPerGallon The volume of each gallon. * #return Total number of gallons needed. */ public static int calcGallonsFuelNeeded(double fuelNeeded, double litersPerGallon) {
double gallonsFuel = Math.ceil(fuelNeeded / litersPerGallon);
return (int) gallonsFuel;//FILL IN THE BODY
}
/**
* Calculates the total cost needed. * * #param gallonsFuel Total number of gallons needed. * #param costPerGallon The cost of each gallon. * #return The total cost of the trip. */ public static double calcCostNeeded(int gallonsFuel, double costPerGallon) { double costNeeded = gallonsFuel * costPerGallon;
return costNeeded;//FILL IN THE BODY
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the distance to be covered (miles):");
double distance;
distance = scnr.nextDouble();
double milesPerLiter = 13.7;
double litersPerGallon = 3.785;
double costPerGallon = 2.629;
scnr.close();
System.out.println("Fuel Needed: " + calcFuelNeeded(distance, milesPerLiter) + " liter(s)");
System.out.println("Gallons needed: " + calcGallonsFuelNeeded( calcFuelNeeded(distance, milesPerLiter), litersPerGallon) + " gallon(s)");
System.out.println("Cost needed: " +calcCostNeeded( calcGallonsFuelNeeded( calcFuelNeeded(distance, milesPerLiter), litersPerGallon), costPerGallon) + " $" );
}
}
Related
I'm trying to calculate trend values of a date value pairs.
I'm using the LinearRegression.java of Robert Sedgewick and Kevin Wayne. https://algs4.cs.princeton.edu/14analysis/LinearRegression.java.html
My trend values returns correct in Google Sheets. https://docs.google.com/spreadsheets/d/1mIBC5EKan3usILDDr0aCFZVtrvf8tdPDV_m7l5opZeQ/edit?usp=sharing
But in my java example they returns mines values. How can i fix this should i use another way?
LinearRegression.java
/**
* The {#code LinearRegression} class performs a simple linear regression
* on an set of <em>n</em> data points (<em>y<sub>i</sub></em>, <em>x<sub>i</sub></em>).
* That is, it fits a straight line <em>y</em> = α + β <em>x</em>,
* (where <em>y</em> is the response variable, <em>x</em> is the predictor variable,
* α is the <em>y-intercept</em>, and β is the <em>slope</em>)
* that minimizes the sum of squared residuals of the linear regression model.
* It also computes associated statistics, including the coefficient of
* determination <em>R</em><sup>2</sup> and the standard deviation of the
* estimates for the slope and <em>y</em>-intercept.
*
* #author Robert Sedgewick
* #author Kevin Wayne
*/
public class LinearRegression {
private final double intercept, slope;
private final double r2;
private final double svar0, svar1;
/**
* Performs a linear regression on the data points {#code (y[i], x[i])}.
*
* #param x the values of the predictor variable
* #param y the corresponding values of the response variable
* #throws IllegalArgumentException if the lengths of the two arrays are not equal
*/
public LinearRegression(double[] x, double[] y) {
if (x.length != y.length) {
throw new IllegalArgumentException("array lengths are not equal");
}
int n = x.length;
// first pass
double sumx = 0.0, sumy = 0.0, sumx2 = 0.0;
for (int i = 0; i < n; i++) {
sumx += x[i];
sumx2 += x[i]*x[i];
sumy += y[i];
}
double xbar = sumx / n;
double ybar = sumy / n;
// second pass: compute summary statistics
double xxbar = 0.0, yybar = 0.0, xybar = 0.0;
for (int i = 0; i < n; i++) {
xxbar += (x[i] - xbar) * (x[i] - xbar);
yybar += (y[i] - ybar) * (y[i] - ybar);
xybar += (x[i] - xbar) * (y[i] - ybar);
}
slope = xybar / xxbar;
intercept = ybar - slope * xbar;
// more statistical analysis
double rss = 0.0; // residual sum of squares
double ssr = 0.0; // regression sum of squares
for (int i = 0; i < n; i++) {
double fit = slope*x[i] + intercept;
rss += (fit - y[i]) * (fit - y[i]);
ssr += (fit - ybar) * (fit - ybar);
}
int degreesOfFreedom = n-2;
r2 = ssr / yybar;
double svar = rss / degreesOfFreedom;
svar1 = svar / xxbar;
svar0 = svar/n + xbar*xbar*svar1;
}
/**
* Returns the <em>y</em>-intercept α of the best of the best-fit line <em>y</em> = α + β <em>x</em>.
*
* #return the <em>y</em>-intercept α of the best-fit line <em>y = α + β x</em>
*/
public double intercept() {
return intercept;
}
/**
* Returns the slope β of the best of the best-fit line <em>y</em> = α + β <em>x</em>.
*
* #return the slope β of the best-fit line <em>y</em> = α + β <em>x</em>
*/
public double slope() {
return slope;
}
/**
* Returns the coefficient of determination <em>R</em><sup>2</sup>.
*
* #return the coefficient of determination <em>R</em><sup>2</sup>,
* which is a real number between 0 and 1
*/
public double R2() {
return r2;
}
/**
* Returns the standard error of the estimate for the intercept.
*
* #return the standard error of the estimate for the intercept
*/
public double interceptStdErr() {
return Math.sqrt(svar0);
}
/**
* Returns the standard error of the estimate for the slope.
*
* #return the standard error of the estimate for the slope
*/
public double slopeStdErr() {
return Math.sqrt(svar1);
}
/**
* Returns the expected response {#code y} given the value of the predictor
* variable {#code x}.
*
* #param x the value of the predictor variable
* #return the expected response {#code y} given the value of the predictor
* variable {#code x}
*/
public double predict(double x) {
return slope*x + intercept;
}
/**
* Returns a string representation of the simple linear regression model.
*
* #return a string representation of the simple linear regression model,
* including the best-fit line and the coefficient of determination
* <em>R</em><sup>2</sup>
*/
public String toString() {
StringBuilder s = new StringBuilder();
s.append(String.format("%.2f n + %.2f", slope(), intercept()));
s.append(" (R^2 = " + String.format("%.3f", R2()) + ")");
return s.toString();
}
}
Main.java
public class Main {
public static void main(String[] args) {
double[] xValues = {1572004656619D, 1572004677789D, 1572004686013D,
1572004693209D, 1572004698606D, 1572004707601D,
1572004726618D};
double[] yValues = {51, 51, 52,
53, 54, 55,
55};
LinearRegression linearRegression = new LinearRegression(xValues, yValues);
System.out.println("Slope: " + linearRegression.slope());
System.out.println("Intercept: " + linearRegression.intercept());
System.out.println("R2: " + linearRegression.R2());
for(int i = 0; i < yValues.length; i++){
System.out.println("time: " + xValues[i] +
" value: " + yValues[i] +
" trend: " + linearRegression.predict(yValues[i]));
}
}
}
Slope: 7.131721781891837E-5
Intercept: -1.1211094805673766E8
R2: 0.8408101880333925
time: 1.572004656619E12 value: 51.0 trend: -1.1211094805310048E8
time: 1.572004677789E12 value: 51.0 trend: -1.1211094805310048E8
time: 1.572004686013E12 value: 52.0 trend: -1.1211094805302916E8
time: 1.572004693209E12 value: 53.0 trend: -1.1211094805295785E8
time: 1.572004698606E12 value: 54.0 trend: -1.1211094805288653E8
time: 1.572004707601E12 value: 55.0 trend: -1.1211094805281521E8
time: 1.572004726618E12 value: 55.0 trend: -1.1211094805281521E8
Solved: I was trying to predict yValues. I changed it to xValues than problem solved.
Main.java
public class Main {
public static void main(String[] args) {
double[] xValues = {1572004656619D, 1572004677789D, 1572004686013D,
1572004693209D, 1572004698606D, 1572004707601D,
1572004726618D};
double[] yValues = {51, 51, 52,
53, 54, 55,
55};
LinearRegression linearRegression = new LinearRegression(xValues, yValues);
System.out.println("Slope: " + linearRegression.slope());
System.out.println("Intercept: " + linearRegression.intercept());
System.out.println("R2: " + linearRegression.R2());
for(int i = 0; i < yValues.length; i++){
System.out.println("time: " + xValues[i] +
" value: " + yValues[i] +
" trend: " + linearRegression.predict(xValues[i]));
}
}
}
Slope: 7.131721781891837E-5
Intercept: -1.1211094805673766E8
R2: 0.8408101880333925
time: 1.572004656619E12 value: 51.0 trend: 50.45171354711056
time: 1.572004677789E12 value: 51.0 trend: 51.96149905025959
time: 1.572004686013E12 value: 52.0 trend: 52.5480118393898
time: 1.572004693209E12 value: 53.0 trend: 53.06121054291725
time: 1.572004698606E12 value: 54.0 trend: 53.44610956311226
time: 1.572004707601E12 value: 55.0 trend: 54.08760794997215
time: 1.572004726618E12 value: 55.0 trend: 55.443847477436066
import java.util.Scanner;
public class clockwise {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the coordinates in a clowise order");
System.out.println("Enter the GPS coordinates for the 1st city: ");
double coordinateX1 = input.nextDouble();
double coordinateY1 = input.nextDouble();
System.out.println("Enter the GPS coordinates for the 2nd city: ");
double coordinateX2 = input.nextDouble();
double coordinateY2 = input.nextDouble();
System.out.println("Enter the GPS coordinates for the 3rd city: ");
double coordinateX3 = input.nextDouble();
double coordinateY3 = input.nextDouble();
System.out.println("Enter the GPS coordinates for the 4th city: ");
double coordinateX4 = input.nextDouble();
double coordinateY4 = input.nextDouble();
//
double earthRadius = 6371.01;
// Get distance
// distance=(radius)arccos(sin(x1)sin(x2)+cos(x1)cos(x2)cos( y1−y2))
// ****************************************************************************1
// 1 35.2270869 -80.8431267
double distance1 = (earthRadius)
* Math.acos(Math.sin(coordinateX1) * Math.sin(coordinateX2))
+ Math.cos(coordinateX1) * Math.cos(coordinateX2)
* Math.cos(coordinateY1 - coordinateY2);
System.out.println("distance1: "+distance1);
// 2 35.2270869 -80.8431267
double distance2 =
(earthRadius)
* Math.acos(Math.sin(coordinateX2) * Math.sin(coordinateX4))
+ Math.cos(coordinateX2) * Math.cos(coordinateX4)
* Math.cos(coordinateY2 - coordinateY4);
System.out.println("distance2: "+distance2);
// 3 28.5383355 -81.3792365
double distance3 = (earthRadius)
* Math.acos(Math.sin(coordinateX4) * Math.sin(coordinateX1))
+ Math.cos(coordinateX4) * Math.cos(coordinateX1)
* Math.cos(coordinateY4 - coordinateY1);
System.out.println("distance3: "+distance3);
// ******************************************************************************2
// 4 33.7489954 -84.3879824
// 1 35.2270869 -80.8431267
double distance01 = (earthRadius)
* Math.acos(Math.sin(coordinateX2) * Math.sin(coordinateX3))
+ Math.cos(coordinateX2) * Math.cos(coordinateX3)
* Math.cos(coordinateY2 - coordinateY3);
// System.out.println("distance: "+distance01);
// 2 32.0835407 -81.0998342
double distance02 = (earthRadius)
* Math.acos(Math.sin(coordinateX3) * Math.sin(coordinateX4))
+ Math.cos(coordinateX3) * Math.cos(coordinateX4)
* Math.cos(coordinateY3 - coordinateY4);
//System.out.println("distance: "+distance02);
// 3 28.5383355 -81.3792365
double distance03 =
(earthRadius)
* Math.acos(Math.sin(coordinateX4) * Math.sin(coordinateX2))
+ Math.cos(coordinateX4) * Math.cos(coordinateX2)
* Math.cos(coordinateY4 - coordinateY2);
// System.out.println("distance: "+distance03);
double rodistance1 = Math.ceil(distance1);
double rodistance2 = Math.ceil(distance1);
double rodistance3 = Math.ceil(distance3);
double rodistance01 = Math.ceil(distance01);
double rodistance02 = Math.ceil(distance02);
double rodistance03 = Math.ceil(distance03);
double s1 = (rodistance1 + rodistance2 + rodistance3) / 2;
double s2 = (rodistance01 + rodistance02 + rodistance03) / 2;
double area1 = Math.sqrt(s1 * (s1 - rodistance1) * (s1 - rodistance2)
* (s1 - rodistance3));
double area2 = Math.sqrt(s2 * (s2 - rodistance01) * (s2 - rodistance02)
* (s2 - rodistance03));
double totalArea = Math.ceil(area1 + area2);
System.out.println("The area is: " + totalArea);
}
}
//SAMPLE
//Please enter the coordinates in a clockwise order.
//Enter the GPS coordinates for the 1st city: 35.2270869 -80.8431267
//Enter the GPS coordinates for the 2nd city: 32.0835407 -81.0998342
//Enter the GPS coordinates for the 3rd city: 28.5383355 -81.3792365
//Enter the GPS coordinates for the 4th city: 33.7489954 -84.3879824
//The area is: 117863.342
I am getting 1.06664794E8 What can I do to get the answer as the sample? Unless I am having errors with my formulas, I should be getting a ok answer. I am using Math.ceil() it might not be what I really wanted I needed to round to 3 decimals .................................................................
Use BigDecimal and setScale()
BigDecimal bg1 = new BigDecimal("1.06664794E8");
// set scale of bg1 to 3 and using CEILING as rounding mode
bg1 = bg1.setScale(3, RoundingMode.CEILING);
System.out.println("After changing the scale to 3 and rounding is "+bg1);
Output:After changing the scale to 3 and rounding is 106664794.000
You can use BigDecimal here
double val = 1.06664794E8;
BigDecimal bigDecimal = new BigDecimal(val);
System.out.println(bigDecimal);
Out put:
106664794
My code compiles, but the output won't show. I think my methods are all correct, but I have no idea why my output will not display. (NB: beginner in Java)
import java.util.Scanner;
import java.lang.Math;
public class Lab8 {
public static void main(String[] args) {
double radius;
double height;
Scanner in = new Scanner(System.in);
System.out.print("Enter radius: ");
radius = in.nextDouble();
System.out.print("Enter height: ");
height = in.nextDouble();
}
public static double Calculations(double radius, double height) {
double surfaceArea = (2 * Math.PI * radius * radius) + (2 * Math.PI * radius * height);
return surfaceArea;
}
public static double calculations(double radius, double height) {
double volume = Math.PI * radius * radius * height;
return volume;
}
public static void output(double surfaceArea, double volume) {
System.out.println("Surface Area of Cylinder: " + surfaceArea);
System.out.println("Voulme of Cylinder: " + volume);
}
}
You need to call your method inside main to print the value.
System.out.println("surfacearea " + Calculations(radius,height));
System.out.println("volume " +calculations(radius,height));
System.out.println("output " + output(radius,height));
Fixed Code:
import java.util.Scanner;
import java.lang.Math;
public class Lab8
{
public static void main(String[] args)
{
double radius;
double height;
Scanner in = new Scanner(System.in);
System.out.print("Enter radius: ");
radius= in.nextDouble();
System.out.print("Enter height: ");
height= in.nextDouble();
System.out.println("surfacearea " + Calculations(radius,height));
System.out.println("volume " +calculations(radius,height));
System.out.println("output " + output(radius,height));
}
public static double Calculations(double radius, double height)
{
double surfaceArea= (2 * Math.PI * radius * radius) + (2 * Math.PI *radius* height);
return surfaceArea;
}
public static double calculations(double radius,double height)
{
double volume= Math.PI * radius * radius * height;
return volume;
}
public static void output(double surfaceArea, double volume)
{
System.out.println("Surface Area of Cylinder: " + surfaceArea);
System.out.println("Voulme of Cylinder: " + volume);
}
}
Try calling one of your Calculations method in your main method, post taking the input such as:
System.out.println(Lab8.Calculations(radius,height));
In main you miss the calculate and output method call
public static void main(String[] args)
{
double radius;
double height;
Scanner in = new Scanner(System.in);
System.out.print("Enter radius: ");
radius= in.nextDouble();
System.out.print("Enter height: ");
height= in.nextDouble();
// call this
System.out.println("area " + output(Calculations(radius,height)));
}
You don't actually call your methods.
In main, after you get the radius and height, call Calculations and calculations respectively, with the appropriate arguments.
Here's an example:
surfaceArea = Calculations(radius, height);
volume = calculations(radius, height);
You didn't call any of your helper functions within main(...). Try adding a call to output or calculations within your main function.
In particular, something like
output(Calculations(radius, height), calculations(radius, height));
will probably suffice.
As you learn Java, it may be helpful to begin applying descriptive names to your functions, such as CylinderSurfaceArea to help keep confusion to a minimum both for you and for anyone who might read code you have written.
I am new to Java and still trying to learn my way around it. Today my teacher gave an assignment where we make a BMI calculator in Java. One of the steps is to make it show the BMI categories. So the user would be able to look at it and see where they stand. I got everything else done but am running into an issue.
Here is the script:
import java.util.Scanner;
public class BMI {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double weight = 0.0;
double height = 0.0;
double bmi = 0.0;
System.out.print("Enter your weight in pounds: ");
weight = input.nextInt();
System.out.print("Enter your height: ");
height = input.nextInt();
bmi = ((weight * 703)/(height * height));
System.out.printf("Your BMI is", bmi);
System.out.println("BMI VALUES");
System.out.println("Underweight: Under 18.5");
System.out.println("Normal: 18.5-24.9 ");
System.out.println("Overweight: 25-29.9");
System.out.println("Obese: 30 or over");
}
}
Here is the result:
Your BMI isBMI VALUES
Underweight: Under 18.5
Normal: 18.5-24.9
Overweight: 25-29.9
Obese: 30 or over
What am I doing wrong and how do I fix this?
You forgot the placeholder for the bmi (and the line terminator):
System.out.printf("Your BMI is %f\n", bmi);
Here's the formatting syntax guide for your reference.
Try this:
System.out.printf("Your BMI is %f\n", bmi);
You can also print like this:
System.out.println("Your BMI is " + bmi);
While you are using printf, the following also works:
System.out.println("Your BMI is " + bmi);
Ideally you should print floats / doubles in a readable format Normally BMI value is measured up to 2 decimal place
System.out.format("Your BMI is %.2f%n",bmi);
You can use arrays like this:
public static void main(String[] args) {
double[] ht = new double[5];
double[] wt = new double[5];
double[] bmi = new double[5];
String[] sht = new String[5];
String[] swt = new String[5];
for (int i = 0; i < ht.length; i++) {
sht[i] = JOptionPane.showInputDialog("Enter Hight");
swt[i] = JOptionPane.showInputDialog("Enter Weight");
ht[i]=Double.parseDouble(sht[i]);
wt[i]=Double.parseDouble(swt[i]);
bmi[i]=wt[i]/(ht[i]*ht[i]);
System.out.println("BMI IS "+bmi[i]+"Kg/m2");
JOptionPane.showMessageDialog(null,"BMI IS "+bmi[i] +"Kg/m2");
if(bmi[i]>25){
JOptionPane.showMessageDialog(null,"YOU ARE AT RISK");
System.out.println("YOU ARE AT RISK");
}else {
JOptionPane.showMessageDialog(null,"YOU ARE Healthy");
System.out.println("YOU ARE Healthy ");
}
}
}
It's probably more coding but you could use JOptionPane
input = JOptionPane.showInputDialog("What is you weight in pounds?");
weight = Double.parseDouble(input);
input = JOptionPane.showInputDialog("What is your hight is inches?");
height = Double.parseDouble(input);
mismatch between variable type declaration (double) and your declaration of user input type (nextInt)
I would use nextDouble as an input type if you want to maintain variable type as a double.
https://github.com/arghadasofficial/BMI/blob/master/src/argha/bmi/Bmi.java
public class Bmi {
//Variables
private double result; //Stores the result
private String bmi; //Stores the Bmi result in String
private String status; //Stores the status (Normal......)
private static DecimalFormat decimalFormat = new DecimalFormat(".#"); //Formating the result
/**
* Get the BMI from calculation and returns the result in String format
*
* #return BMI
*/
public String getBmi() {
/**
* Following code example : bmi = decimalFormat.format(result);
*
* if bmi is 23.12345 then remove 2345 and return 23.1 using DecimalFormat class provided by Java
*
*/
bmi = decimalFormat.format(result);
return bmi;
}
/**
* Get the status according to the BMI result and returns the Status in
* String format
*
* #return Status
*/
public String getStatus() {
return status;
}
/**
* Get weight and height in double format and do the calculation for you
*
* #param weight - accepts weight in kilograms
* #param height - accept height in centimeters
*/
public void calculateBmi(double weight, double height) {
/**
* First get weight and height then convert height to meters then
* multiply the height itself to height and then divide the height with
* weight then set the actual value to result variable
*/
//Convert the height from cm to m
double meters = height / 100;
//Multiply height by height
double multiply = meters * meters;
//divide the height with weight in kg
double division = weight / multiply;
//set the value to result variable
result = division;
//call checkStatus method for checking Status
checkStatus();
}
/**
* Private method for checking bmi and returns the status It remains private
* because we don't need to access this from somewhere else.
*/
private void checkStatus() {
/**
* Check :
*
* if BMI is less than 18.5 then set status to Underweight if BMI is
* greater than 18.5 and less than 25 then set status to Normal if BMI
* is greater than 25 and less than 30 then set status to Overweight if
* BMI equals to 30 or greater than 30 then set status to Obese
*/
if (result < 18.5) {
status = "Underweight";
} else if (result > 18.5 && result < 25) {
status = "Normal";
} else if (result > 25 && result < 30) {
status = "Overweight";
} else if (result == 30 || result > 30) {
status = "Obese";
}
}
}
A: I am not sure that bmi = ((weight * 703)/(height * height)); is right.
I came across a formula which might work for you
BMI = ((weight/(height * height))* 10000;
B: System.out.printf(“Your BMI is”, bmi); is not needed
System.out.prinln( “ Your BMI is “ + BMI);
I hope it work for you
best of luck keep it up
Does Java have a class for complex numbers?
There's an Apache Commons one called Complex. I don't believe the JDK has one.
No, the JDK does not have one but here is an implementation I have written.
Here is the GITHUB project.
/**
* <code>ComplexNumber</code> is a class which implements complex numbers in Java.
* It includes basic operations that can be performed on complex numbers such as,
* addition, subtraction, multiplication, conjugate, modulus and squaring.
* The data type for Complex Numbers.
* <br /><br />
* The features of this library include:<br />
* <ul>
* <li>Arithmetic Operations (addition, subtraction, multiplication, division)</li>
* <li>Complex Specific Operations - Conjugate, Inverse, Absolute/Magnitude, Argument/Phase</li>
* <li>Trigonometric Operations - sin, cos, tan, cot, sec, cosec</li>
* <li>Mathematical Functions - exp</li>
* <li>Complex Parsing of type x+yi</li>
* </ul>
*
* #author Abdul Fatir
* #version 1.1
*
*/
public class ComplexNumber
{
/**
* Used in <code>format(int)</code> to format the complex number as x+yi
*/
public static final int XY = 0;
/**
* Used in <code>format(int)</code> to format the complex number as R.cis(theta), where theta is arg(z)
*/
public static final int RCIS = 1;
/**
* The real, Re(z), part of the <code>ComplexNumber</code>.
*/
private double real;
/**
* The imaginary, Im(z), part of the <code>ComplexNumber</code>.
*/
private double imaginary;
/**
* Constructs a new <code>ComplexNumber</code> object with both real and imaginary parts 0 (z = 0 + 0i).
*/
public ComplexNumber()
{
real = 0.0;
imaginary = 0.0;
}
/**
* Constructs a new <code>ComplexNumber</code> object.
* #param real the real part, Re(z), of the complex number
* #param imaginary the imaginary part, Im(z), of the complex number
*/
public ComplexNumber(double real, double imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
/**
* Adds another <code>ComplexNumber</code> to the current complex number.
* #param z the complex number to be added to the current complex number
*/
public void add(ComplexNumber z)
{
set(add(this,z));
}
/**
* Subtracts another <code>ComplexNumber</code> from the current complex number.
* #param z the complex number to be subtracted from the current complex number
*/
public void subtract(ComplexNumber z)
{
set(subtract(this,z));
}
/**
* Multiplies another <code>ComplexNumber</code> to the current complex number.
* #param z the complex number to be multiplied to the current complex number
*/
public void multiply(ComplexNumber z)
{
set(multiply(this,z));
}
/**
* Divides the current <code>ComplexNumber</code> by another <code>ComplexNumber</code>.
* #param z the divisor
*/
public void divide(ComplexNumber z)
{
set(divide(this,z));
}
/**
* Sets the value of current complex number to the passed complex number.
* #param z the complex number
*/
public void set(ComplexNumber z)
{
this.real = z.real;
this.imaginary = z.imaginary;
}
/**
* Adds two <code>ComplexNumber</code>.
* #param z1 the first <code>ComplexNumber</code>.
* #param z2 the second <code>ComplexNumber</code>.
* #return the resultant <code>ComplexNumber</code> (z1 + z2).
*/
public static ComplexNumber add(ComplexNumber z1, ComplexNumber z2)
{
return new ComplexNumber(z1.real + z2.real, z1.imaginary + z2.imaginary);
}
/**
* Subtracts one <code>ComplexNumber</code> from another.
* #param z1 the first <code>ComplexNumber</code>.
* #param z2 the second <code>ComplexNumber</code>.
* #return the resultant <code>ComplexNumber</code> (z1 - z2).
*/
public static ComplexNumber subtract(ComplexNumber z1, ComplexNumber z2)
{
return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);
}
/**
* Multiplies one <code>ComplexNumber</code> to another.
* #param z1 the first <code>ComplexNumber</code>.
* #param z2 the second <code>ComplexNumber</code>.
* #return the resultant <code>ComplexNumber</code> (z1 * z2).
*/
public static ComplexNumber multiply(ComplexNumber z1, ComplexNumber z2)
{
double _real = z1.real*z2.real - z1.imaginary*z2.imaginary;
double _imaginary = z1.real*z2.imaginary + z1.imaginary*z2.real;
return new ComplexNumber(_real,_imaginary);
}
/**
* Divides one <code>ComplexNumber</code> by another.
* #param z1 the first <code>ComplexNumber</code>.
* #param z2 the second <code>ComplexNumber</code>.
* #return the resultant <code>ComplexNumber</code> (z1 / z2).
*/
public static ComplexNumber divide(ComplexNumber z1, ComplexNumber z2)
{
ComplexNumber output = multiply(z1,z2.conjugate());
double div = Math.pow(z2.mod(),2);
return new ComplexNumber(output.real/div,output.imaginary/div);
}
/**
* The complex conjugate of the current complex number.
* #return a <code>ComplexNumber</code> object which is the conjugate of the current complex number
*/
public ComplexNumber conjugate()
{
return new ComplexNumber(this.real,-this.imaginary);
}
/**
* The modulus, magnitude or the absolute value of current complex number.
* #return the magnitude or modulus of current complex number
*/
public double mod()
{
return Math.sqrt(Math.pow(this.real,2) + Math.pow(this.imaginary,2));
}
/**
* The square of the current complex number.
* #return a <code>ComplexNumber</code> which is the square of the current complex number.
*/
public ComplexNumber square()
{
double _real = this.real*this.real - this.imaginary*this.imaginary;
double _imaginary = 2*this.real*this.imaginary;
return new ComplexNumber(_real,_imaginary);
}
/**
* #return the complex number in x + yi format
*/
#Override
public String toString()
{
String re = this.real+"";
String im = "";
if(this.imaginary < 0)
im = this.imaginary+"i";
else
im = "+"+this.imaginary+"i";
return re+im;
}
/**
* Calculates the exponential of the <code>ComplexNumber</code>
* #param z The input complex number
* #return a <code>ComplexNumber</code> which is e^(input z)
*/
public static ComplexNumber exp(ComplexNumber z)
{
double a = z.real;
double b = z.imaginary;
double r = Math.exp(a);
a = r*Math.cos(b);
b = r*Math.sin(b);
return new ComplexNumber(a,b);
}
/**
* Calculates the <code>ComplexNumber</code> to the passed integer power.
* #param z The input complex number
* #param power The power.
* #return a <code>ComplexNumber</code> which is (z)^power
*/
public static ComplexNumber pow(ComplexNumber z, int power)
{
ComplexNumber output = new ComplexNumber(z.getRe(),z.getIm());
for(int i = 1; i < power; i++)
{
double _real = output.real*z.real - output.imaginary*z.imaginary;
double _imaginary = output.real*z.imaginary + output.imaginary*z.real;
output = new ComplexNumber(_real,_imaginary);
}
return output;
}
/**
* Calculates the sine of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the sine of z.
*/
public static ComplexNumber sin(ComplexNumber z)
{
double x = Math.exp(z.imaginary);
double x_inv = 1/x;
double r = Math.sin(z.real) * (x + x_inv)/2;
double i = Math.cos(z.real) * (x - x_inv)/2;
return new ComplexNumber(r,i);
}
/**
* Calculates the cosine of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the cosine of z.
*/
public static ComplexNumber cos(ComplexNumber z)
{
double x = Math.exp(z.imaginary);
double x_inv = 1/x;
double r = Math.cos(z.real) * (x + x_inv)/2;
double i = -Math.sin(z.real) * (x - x_inv)/2;
return new ComplexNumber(r,i);
}
/**
* Calculates the tangent of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the tangent of z.
*/
public static ComplexNumber tan(ComplexNumber z)
{
return divide(sin(z),cos(z));
}
/**
* Calculates the co-tangent of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the co-tangent of z.
*/
public static ComplexNumber cot(ComplexNumber z)
{
return divide(new ComplexNumber(1,0),tan(z));
}
/**
* Calculates the secant of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the secant of z.
*/
public static ComplexNumber sec(ComplexNumber z)
{
return divide(new ComplexNumber(1,0),cos(z));
}
/**
* Calculates the co-secant of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the co-secant of z.
*/
public static ComplexNumber cosec(ComplexNumber z)
{
return divide(new ComplexNumber(1,0),sin(z));
}
/**
* The real part of <code>ComplexNumber</code>
* #return the real part of the complex number
*/
public double getRe()
{
return this.real;
}
/**
* The imaginary part of <code>ComplexNumber</code>
* #return the imaginary part of the complex number
*/
public double getIm()
{
return this.imaginary;
}
/**
* The argument/phase of the current complex number.
* #return arg(z) - the argument of current complex number
*/
public double getArg()
{
return Math.atan2(imaginary,real);
}
/**
* Parses the <code>String</code> as a <code>ComplexNumber</code> of type x+yi.
* #param s the input complex number as string
* #return a <code>ComplexNumber</code> which is represented by the string.
*/
public static ComplexNumber parseComplex(String s)
{
s = s.replaceAll(" ","");
ComplexNumber parsed = null;
if(s.contains(String.valueOf("+")) || (s.contains(String.valueOf("-")) && s.lastIndexOf('-') > 0))
{
String re = "";
String im = "";
s = s.replaceAll("i","");
s = s.replaceAll("I","");
if(s.indexOf('+') > 0)
{
re = s.substring(0,s.indexOf('+'));
im = s.substring(s.indexOf('+')+1,s.length());
parsed = new ComplexNumber(Double.parseDouble(re),Double.parseDouble(im));
}
else if(s.lastIndexOf('-') > 0)
{
re = s.substring(0,s.lastIndexOf('-'));
im = s.substring(s.lastIndexOf('-')+1,s.length());
parsed = new ComplexNumber(Double.parseDouble(re),-Double.parseDouble(im));
}
}
else
{
// Pure imaginary number
if(s.endsWith("i") || s.endsWith("I"))
{
s = s.replaceAll("i","");
s = s.replaceAll("I","");
parsed = new ComplexNumber(0, Double.parseDouble(s));
}
// Pure real number
else
{
parsed = new ComplexNumber(Double.parseDouble(s),0);
}
}
return parsed;
}
/**
* Checks if the passed <code>ComplexNumber</code> is equal to the current.
* #param z the complex number to be checked
* #return true if they are equal, false otherwise
*/
#Override
public final boolean equals(Object z)
{
if (!(z instanceof ComplexNumber))
return false;
ComplexNumber a = (ComplexNumber) z;
return (real == a.real) && (imaginary == a.imaginary);
}
/**
* The inverse/reciprocal of the complex number.
* #return the reciprocal of current complex number.
*/
public ComplexNumber inverse()
{
return divide(new ComplexNumber(1,0),this);
}
/**
* Formats the Complex number as x+yi or r.cis(theta)
* #param format_id the format ID <code>ComplexNumber.XY</code> or <code>ComplexNumber.RCIS</code>.
* #return a string representation of the complex number
* #throws IllegalArgumentException if the format_id does not match.
*/
public String format(int format_id) throws IllegalArgumentException
{
String out = "";
if(format_id == XY)
out = toString();
else if(format_id == RCIS)
{
out = mod()+" cis("+getArg()+")";
}
else
{
throw new IllegalArgumentException("Unknown Complex Number format.");
}
return out;
}
}
The JDK doesn't current have any classes for complex numbers, unfortunately.
You could have a look at:
http://www.java2s.com/Code/Java/Data-Type/Thisclassrepresentscomplexnumbersanddefinesmethodsforperformingarithmeticoncomplexnumbers.htm
which provides an implementation you may find useful.