Issue with returning an equation in Java - java

I'm having an issue with my function call. I'm trying to find the solution to the two-point boundary value problem x' = f(t,x) = x + 0.09 x 2 + cos(10 t) with boundary condition x(0) + x(1) - 3.0 = 0 using the secant and third-order Runge-Kutta methods and for whatever reason, my equation method gives me four errors on a single line, those being that it's not a statement, is missing two semicolons, and is missing an end parenthesis.
public class BoundaryValueProblem
{
public static double f(double t, double x)
{
return x + 0.09x^2 + Math.cos(10t);
}
public static void findZero
{
double x4;
double x5 = .7;
double x6 = 1.0;
int n = 1;
double fx;
double f1;
double f2;
double Error;
BoundaryValueProblem FZ = new BoundaryValueProblem();
f1 = FZ.f(1.0, 1.0);
f2 = FZ.f(1.0, 1.0);
System.out.println("Secant Method");
System.out.println("n: \t\t x1: \t\t x2: \t\t Error:");
while(abs(x5 + x6 - 3.0) < 1e-5)
{
x4 = x6 - f2 * ((x6 - x5)/(f2 - f1));
fx = FZ.f(1.0, 1.0);
x5 = x6;
x6 = x4;
f1 = f2;
f2 = fx;
Error = x5 + x6 - 3.0;
System.out.println(n + "\t\t" + x5 + "\t\t" + x6 + "\t\t" + Error);
n++;
}
System.out.println();
}
public void rkm(double x0, double t0, double h)
{
double x1, x2, x3;
int i=0;
double a1 = 0.5;
double a2 = 0.25;
double c0 = 2.0/3.0;
double c1 = 5.0/3.0;
double c2 = -4.0/3.0;
double b21 = -.25;
double b10 = .5;
double b20 = .5;
double stepsize = .025;
System.out.println("Runge-Kutta Method:");
System.out.println("i: \t\t h: \t\t t0: \t\t x0:");
System.out.println(i + "\t\t " + h + "\t\t " + t0 + "\t\t " + x0 );
for(i = 0; i < 40; i++)
{
x1 = x0 + h * b10 * f(t0, x0);
x2 = x0 + h * (b20 * f(t0, x0) + b21 * f(t0 + a1 * h, x1));
x3 = x0 + h * (c0 * f(t0, x0) + c1 * f(t0 + a1 * h, x1) + c2 * f(t0 + a2 * h, x2));
t0 = t0 + stepsize;
x0 = x3;
System.out.println(i + "\t\t " + h + "\t\t " + t0 + "\t\t " + x0 );
}
System.out.println();
}
public static void main(String[] args)
{
BoundaryValueProblem FZ1 = new BoundaryValueProblem();
FZ1.findZero();
BoundaryValueProblem RKM1 = new BoundaryValueProblem();
RKM1.rkm(1.0, 0.0, 0.0);
}
}
I've had it work on simpler equations but this one is not working for me. I have the rest of the code mostly correct (I believe), but I don't think it's the cause of the error since I commented it out and the errors persisted, thus I'm not focused on that. Any advice or help would be greatly appreciated.

Below is fixed code. Please remember that java unlike Octave or Matlab requires multiplication operator (*) and doesn't support pow operator (^) - you would need to use Math.pow() instead.
public class BoundaryValueProblem {
public static double f(double t, double x) {
return x + 0.09 * x * x + Math.cos(10 * t);
}
public static void findZero() {
double x4;
double x5 = .7;
double x6 = 1.0;
int n = 1;
double fx;
double f1;
double f2;
double Error;
f1 = f(1.0, 1.0);
f2 = f(1.0, 1.0);
System.out.println("Secant Method");
System.out.println("n: \t\t x1: \t\t x2: \t\t Error:");
while (Math.abs(x5 + x6 - 3.0) < 1e-5) {
x4 = x6 - f2 * ((x6 - x5) / (f2 - f1));
fx = f(1.0, 1.0);
x5 = x6;
x6 = x4;
f1 = f2;
f2 = fx;
Error = x5 + x6 - 3.0;
System.out.println(n + "\t\t" + x5 + "\t\t" + x6 + "\t\t" + Error);
n++;
}
System.out.println();
}
public void rkm(double x0, double t0, double h) {
double x1, x2, x3;
int i = 0;
double a1 = 0.5;
double a2 = 0.25;
double c0 = 2.0 / 3.0;
double c1 = 5.0 / 3.0;
double c2 = -4.0 / 3.0;
double b21 = -.25;
double b10 = .5;
double b20 = .5;
double stepsize = .025;
System.out.println("Runge-Kutta Method:");
System.out.println("i: \t\t h: \t\t t0: \t\t x0:");
System.out.println(i + "\t\t " + h + "\t\t " + t0 + "\t\t " + x0);
for (i = 0; i < 40; i++) {
x1 = x0 + h * b10 * f(t0, x0);
x2 = x0 + h * (b20 * f(t0, x0) + b21 * f(t0 + a1 * h, x1));
x3 = x0 + h * (c0 * f(t0, x0) + c1 * f(t0 + a1 * h, x1) + c2 * f(t0 + a2 * h, x2));
t0 = t0 + stepsize;
x0 = x3;
System.out.println(i + "\t\t " + h + "\t\t " + t0 + "\t\t " + x0);
}
System.out.println();
}
/**
* #param args
*/
public static void main(String[] args) {
BoundaryValueProblem FZ1 = new BoundaryValueProblem();
FZ1.findZero();
BoundaryValueProblem RKM1 = new BoundaryValueProblem();
RKM1.rkm(1.0, 0.0, 0.0);
}
}

public static void findZero// correct this. Where are parenthesis () for this method
{
double x4;
double x5 = .7;
double x6 = 1.0;
int n = 1;
double fx;
double f1;
double f2;
double Error;
BoundaryValueProblem FZ = new BoundaryValueProblem();
f1 = FZ.f(1.0, 1.0);
f2 = FZ.f(1.0, 1.0);
System.out.println("Secant Method");
System.out.println("n: \t\t x1: \t\t x2: \t\t Error:");
while(abs(x5 + x6 - 3.0) < 1e-5)
{
x4 = x6 - f2 * ((x6 - x5)/(f2 - f1));
fx = FZ.f(1.0, 1.0);
x5 = x6;
x6 = x4;
f1 = f2;
f2 = fx;
Error = x5 + x6 - 3.0;
System.out.println(n + "\t\t" + x5 + "\t\t" + x6 + "\t\t" + Error);
n++;
}
System.out.println();
}

There is a method without parentheses: public static void findZero
It should be public static void findZero()

Function findZero should have parenthesis at the end like this:
public static void findZero()
return x + 0.09x^2 + Math.cos(10t);
In Java you have to put math operator between operands so instead of 0.09x you have to write 0.09*x and instead of 10t you have to write 10*t
^ sign is XOR operator not power operator so you have to use Math.pow function (I'm guessing that's what you wanted to do)
In the end this line should look like this:
return x + Math.pow(0.09*x, 2) + Math.cos(10*t);
I'm also getting error with abs function. I don't know if you wrote that function yourself but if you didn't you should use Math.abs function

Related

How to write a cosine theorem using Java?

How to write this theorem correctly as is written in the formula?
package com.company;
public class Exercise8 {
public static void main(String[] args) {
double AB = 6;
double AC = 16;
double Angle = 60;
double CosOfAngle = 0.5;
// Почему-то значение косинуса 60 градусов вместо 0.5, пишет
// -0.9524129804151563 ? ? ? (Do not pay attention)
// Formula is BC^2 = AB^2 + AC^2 - 2AB*AC * cos A
double bc = (2 * (Math.pow(AB, 2) + Math.pow(AC, 2) - ((AB * AC))) * CosOfAngle);
double BC = Math.sqrt(bc);
double P = AB + BC + AC;
double p = 0.5 * P; // Где p - полупериметр
double S0 = (p * ((p - AB) * (p - BC) * (p - AC)));
double S1 = Math.sqrt(S0);
double S = Math.round(S1);
System.out.println("Perimeter of triangle is : " + P + " cm ");
System.out.println("Area of triangle is : " + S + " cm^2 ");
}
}
The mistake is in this line:
double bc = (2 * (Math.pow(AB, 2) + Math.pow(AC, 2) - ((AB * AC))) * CosOfAngle);
which should be:
double bc = Math.pow(AB, 2) + Math.pow(AC, 2) - 2 * AB * AC * CosOfAngle;
You were multiplying the whole formula by 2, whereas only the cosine part needs to be multiplied by two. There were too many confusing parenthesis. Removing them made it a lot clearer.
This seems simple to me:
// https://www.mathsisfun.com/algebra/trig-cosine-law.html
public double lawOfCosines(double a, double b, double angleInRadians) {
return Math.sqrt(a*a + b*b - 2.0*a*b*Math.cos(angleInRadians));
}

How do I use a JOptionPane input from a test class in another class?

I currently have a Triangle class with all of my calculations.
public class Triangle
{
private double x1;
private double y1;
private double x2;
private double y2;
private double x3;
private double y3;
private double lengthA;
private double lengthB;
private double lengthC;
private double angleA;
private double angleB;
private double angleC;
private double perimeter;
private double height;
private double area;
public double calcArea()
{
area = .5 * lengthC * height;
return area;
}
public double calcPerimeter()
{
perimeter = lengthA + lengthB + lengthC;
return perimeter;
}
public double lengthA()
{
lengthA = Math.sqrt(Math.pow((x2 - x3),2) + Math.pow(height,2));
return lengthA;
}
public double lengthB()
{
lengthB = Math.sqrt(Math.pow((x3 - x1),2) + Math.pow(height,2));
return lengthB;
}
public double lengthC()
{
lengthC = x2 - x1;
return lengthC;
}
public double getHeight()
{
height = y3 - y1;
return height;
}
public double angleA()
{
angleA = Math.abs(Math.toDegrees(Math.asin(height / lengthB)));
return angleA;
}
public double angleB()
{
angleB = Math.abs(Math.toDegrees(Math.asin(height / lengthA)));
return angleB;
}
public double angleC()
{
angleC = 180 - angleA - angleB;
return angleC;
}
}
I also have a TriangleTester class that uses JOptionPane to get coordinates for the triangle.
import javax.swing.*;
public class TriangleTester
{
public static void main (String [] args)
{
double x1;
double y1;
double x2;
double y2;
double x3;
double y3;
String v1;
String v2;
String v3;
String v4;
String v5;
String v6;
v1 = JOptionPane.showInputDialog("Enter x1 for point A");
v2 = JOptionPane.showInputDialog("Enter y1 for point A");
v3 = JOptionPane.showInputDialog("Enter x2 for point B");
v4 = JOptionPane.showInputDialog("Enter y2 for point B");
v5 = JOptionPane.showInputDialog("Enter x3 for point C");
v6 = JOptionPane.showInputDialog("Enter y3 for point C");
x1 = Integer.parseInt(v1);
y1 = Integer.parseInt(v2);
x2 = Integer.parseInt(v3);
y2 = Integer.parseInt(v4);
x3 = Integer.parseInt(v5);
y3 = Integer.parseInt(v6);
Triangle tri = new Triangle();
double lengthA = tri.lengthA();
double lengthB = tri.lengthB();
double lengthC = tri.lengthC();
double angleA = tri.angleA();
double angleB = tri.angleB();
double angleC = tri.angleC();
double perimeter = tri.calcPerimeter();
double height = tri.getHeight();
double area = tri.calcArea();
System.out.printf("Set up triangle with coordinates (" + x1 + "," + y1 + "), (" + x2 + "," + y2 + "), (" + x3 + "," + y3 + ")");
System.out.printf("\nArea:\t\t\t\t" + area);
System.out.printf("\nPerimeter:\t\t" + perimeter);
System.out.printf("\nLength side a:\t" + lengthA);
System.out.printf("\nLength side b:\t" + lengthB);
System.out.printf("\nLength side c:\t" + lengthC);
System.out.printf("\nHeight h:\t\t" + height);
System.out.printf("\nAngle A:\t\t\t" + angleA);
System.out.printf("\nAngle B:\t\t\t" + angleB);
System.out.printf("\nAngle C:\t\t\t" + angleC);
}
}
When I run the tester code, it prints the coordinates with the correct x and y values, but everything else ends up printing as 0. I believe this is because I have not made any connection between the x and y values of the Triangle class and the TriangleTester class. How can I get the Triangle class to use the inputted x and y values from the TriangleTester class to calculate the answers? Thanks.
The main idea here was you were using a getter as a setter.
You were not passing the data for the setter methods between classes
Main program
package triangles;
import javax.swing.*;
public class Triangles {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
double x1;
double y1;
double x2;
double y2;
double x3;
double y3;
String v1;
String v2;
String v3;
String v4;
String v5;
String v6;
v1 = JOptionPane.showInputDialog("Enter x1 for point A");
v2 = JOptionPane.showInputDialog("Enter y1 for point A");
v3 = JOptionPane.showInputDialog("Enter x2 for point B");
v4 = JOptionPane.showInputDialog("Enter y2 for point B");
v5 = JOptionPane.showInputDialog("Enter x3 for point C");
v6 = JOptionPane.showInputDialog("Enter y3 for point C");
x1 = Integer.parseInt(v1);
y1 = Integer.parseInt(v2);
x2 = Integer.parseInt(v3);
y2 = Integer.parseInt(v4);
x3 = Integer.parseInt(v5);
y3 = Integer.parseInt(v6);
Triangle tri = new Triangle();
//set all needed data
tri.setLengthA(x2,x3);
tri.setLengthB(x3,x1);
tri.setLengthC(x2,x1);
tri.setHeight(y3,y1);
// set calculations off the data
tri.setAngleA();
tri.setAngleB();
tri.setAngleC();
double perimeter = tri.calcPerimeter();
double area = tri.calcArea();
System.out.printf("Set up triangle with coordinates (" + x1 + "," + y1 + "), (" + x2 + "," + y2 + "), (" + x3 + "," + y3 + ")");
System.out.printf("\nArea:\t\t\t\t" + area);
System.out.printf("\nPerimeter:\t\t" + perimeter);
System.out.printf("\nLength side a:\t" + tri.lengthA);
System.out.printf("\nLength side b:\t" + tri.lengthB);
System.out.printf("\nLength side c:\t" + tri.lengthC);
System.out.printf("\nHeight h:\t\t" + tri.height);
System.out.printf("\nAngle A:\t\t\t" + tri.angleA);
System.out.printf("\nAngle B:\t\t\t" + tri.angleB);
System.out.printf("\nAngle C:\t\t\t" + tri.angleC);
}
}
and your class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package triangles;
/**
*
* #author jstil
*/
public class Triangle {
private double x1;
private double y1;
private double x2;
private double y2;
private double x3;
private double y3;
public double lengthA;
public double lengthB;
public double lengthC;
public double angleA;
public double angleB;
public double angleC;
private double perimeter;
public double height;
private double area;
public double calcArea()
{
area = .5 * lengthC * height;
return area;
}
public double calcPerimeter()
{
perimeter = lengthA + lengthB + lengthC;
return perimeter;
}
public void setLengthA( double x2 , double x3)
{
lengthA = Math.sqrt(Math.pow((x2 - x3),2) + Math.pow(height,2));
}
public void setLengthB(double x3, double x1)
{
lengthB = Math.sqrt(Math.pow((x3 - x1),2) + Math.pow(height,2));
}
public void setLengthC(double x2, double x1)
{
lengthC = x2 - x1;
}
public void setHeight(double y3, double y1)
{
height = y3 - y1;
}
public void setAngleA()
{
angleA = Math.abs(Math.toDegrees(Math.asin(height/ lengthB)));
}
public void setAngleB()
{
angleB = Math.abs(Math.toDegrees(Math.asin(height / lengthA)));
}
public void setAngleC()
{
angleC = 180 - angleA - angleB;
}
}

Placement of Math.toRadians for solving quadratic and cubic equations

I am writing a program which solves either quadratic or cubic equations. The thing is that I don't know if I am placing the Math.toRadians correctly.
The code is the following:
public double[] getRaices(double a,double b, double c, double d) throws ComplexException {
if (a==0){
double discriminante=Math.pow(c,2)+((-4)*b*d);
if(discriminante>=0){
this.Raices[0]=(c*(-1)+Math.sqrt(discriminante))/(2*b);
this.Raices[1]=(c*(-1)-Math.sqrt(discriminante))/(2*b);
}else{
throw new ComplexException("No hay solucion Real");
}
} else{
double f=((3*c/a)-(Math.pow(b,2)/Math.pow(a,2)))/3;
double g=((2*Math.pow(b,3)/Math.pow(a,3))-(9*b*c/Math.pow(a,2))+(27*d/a))/27;
double h=(Math.pow(g,2)/4)+(Math.pow(f,3)/27);
if(f+g+h==0){
Raices [0]=Math.cbrt(d/a)*(-1);
Raices [1]=Math.cbrt(d/a)*(-1);
Raices [2]=Math.cbrt(d/a)*(-1);
}else{
if(h<=0){
double i=Math.sqrt((Math.pow(g,2)/4)-h);
double j=Math.cbrt(i);
double k=Math.acos(Math.toRadians(-1*(g/2*i)));
System.out.println(" "+k+" ");
double l=j*(0-1);
double m=Math.toRadians(Math.cos(Math.toRadians(k/3)));
System.out.println(" "+m+" ");
double n=Math.sqrt(3)*Math.sin(Math.toRadians(k/3));
System.out.println(" "+n+" ");
double p=(b/(3*a)*(0-1));
Raices [0]=2*j*Math.cos(Math.toRadians(k/3))-(b/(3*a));
Raices [1]=(l*(m+n))+p;
Raices [2]=(l*(m-n))+p;
}else{
double r=((0-1)*(g/2))+Math.sqrt(h);
double s=Math.cbrt(r);
double t=((0-1)*(g/2))-Math.sqrt(h);
double u=Math.cbrt(t);
throw new ComplexException("2 de las raices son imaginarias pero una raiz es real: "+Math.floor(Raices [0]=(s+u)-(b/(3*a))));
}
}
}
return Raices;
}
But the problem is in the if (h<=0).
I tested your code against the web page and found several errors.
First is g /2i, you wrote g/2*i instead of g/2/i or (g/(2*i). And several Math.toRadians not necessary (webpage said calculations is in radians, so no need to convert).
I added println to help following the formula :
package test;
public class Cubic {
private double[] Raices = new double[3];
public static void main(String[] args) throws ComplexException {
double[] raices = new Cubic().getRaices(2, -4, -22, 24);
System.out.println(raices[0] + "," + raices[1] + "," + raices[2]);
}
public double[] getRaices(double a, double b, double c, double d) throws ComplexException {
if (a == 0) {
double discriminante = Math.pow(c, 2) + ((-4) * b * d);
if (discriminante >= 0) {
this.Raices[0] = (c * (-1) + Math.sqrt(discriminante)) / (2 * b);
this.Raices[1] = (c * (-1) - Math.sqrt(discriminante)) / (2 * b);
} else {
throw new ComplexException("No hay solucion Real");
}
} else {
double f = ((3 * c / a) - (Math.pow(b, 2) / Math.pow(a, 2))) / 3;
System.out.println("f=" + f);
double g = ((2 * Math.pow(b, 3) / Math.pow(a, 3)) - (9 * b * c / Math.pow(a, 2)) + (27 * d / a)) / 27;
System.out.println("g=" + g);
double h = (Math.pow(g, 2) / 4) + (Math.pow(f, 3) / 27);
System.out.println("h=" + h);
if (f + g + h == 0) {
Raices[0] = Math.cbrt(d / a) * (-1);
Raices[1] = Math.cbrt(d / a) * (-1);
Raices[2] = Math.cbrt(d / a) * (-1);
} else {
if (h <= 0) {
double i = Math.sqrt((Math.pow(g, 2) / 4) - h);
double j = Math.cbrt(i);
double k = Math.acos(-1 * (g / 2 / i));
System.out.println("k=" + k + " ");
double l = j * (0 - 1);
System.out.println("l=" + l + " ");
double m = Math.cos(k / 3);
System.out.println("m= " + m + " ");
double n = Math.sqrt(3) * Math.sin(k / 3);
System.out.println("n= " + n + " ");
double p = (b / (3 * a) * (0 - 1));
System.out.println("p= " + p + " ");
Raices[0] = 2 * j * Math.cos(k / 3) - (b / (3 * a));
Raices[1] = (l * (m + n)) + p;
Raices[2] = (l * (m - n)) + p;
} else {
double r = ((0 - 1) * (g / 2)) + Math.sqrt(h);
double s = Math.cbrt(r);
double t = ((0 - 1) * (g / 2)) - Math.sqrt(h);
double u = Math.cbrt(t);
throw new ComplexException(
"2 de las raices son imaginarias pero una raiz es real: " + Math.floor(Raices[0] = (s + u) - (b / (3 * a))));
}
}
}
return Raices;
}
}

basic math equation math to java code

so i have a math equation that i need to use in java but for some reason my code is giving me small errors :(
the math equation is describe on this web page in the section extra credit
my current code outpouts 4000 and the answere is 4005 what am i duing wrong ?
my test class lookes like this
public class MainActivity {
public static void main(String[] args) throws Exception{
double baseMaterial =556;
int me =5;
int ml = 10;
int extraMaterial = 3444;
System.out.println(""+calculateMiniralTotal(baseMaterial,me,ml,extraMaterial));
}
public static double calculateMiniralTotal(double perfekt,int me,int ml,int extraMaterial) {
double s = (perfekt + (perfekt * (10 / (ml + 1)) / 100));
s = Math.round(s);
double r = s + (perfekt * (0.25 - (0.05 * me)));
r = Math.round(r);
double q = extraMaterial + (extraMaterial * (0.25 - (0.05 * me)));
q = Math.round(q);
//double r=q;
r = r + q;
return Math.round(r);
}
}
You are performing integer division with (10 / (ml + 1)) / 100, which in Java must result in another int. Your ml is 10, and in Java, 10 / 11 is 0, not 0.909..., and nothing is added to s.
Use a double literal or cast to double to force floating-point computations.
double s = (perfekt + (perfekt * (10.0 / (ml + 1)) / 100));
or
double s = (perfekt + (perfekt * ( (double) 10 / (ml + 1)) / 100));
Making either change makes the output:
4005.0
When you multiply a double by an int you get an int back.
public class Main
{
public static void main(String[] args)
throws Exception
{
double baseMaterial = 556;
int me = 5;
int ml = 10;
int extraMaterial = 3444;
System.out.println("" + calculateMiniralTotal(baseMaterial, me, ml, extraMaterial));
}
public static double calculateMiniralTotal(double perfekt, int me, int ml, int extraMaterial)
{
double s = (perfekt + (perfekt * (10.0 / (ml + 1)) / 100.0)); // <-- changed from 10 to 10.0 and 100 to 100.0. This way they are doubles too
s = Math.round(s);
double r = s + (perfekt * (0.25 - (0.05 * me)));
r = Math.round(r);
double q = extraMaterial + (extraMaterial * (0.25 - (0.05 * me)));
q = Math.round(q);
// double r=q;
r = r + q;
return Math.round(r);
}
}

Find Two Points In A Three-Dimensional Space Nearest To Each Other

As the title suggests, I'm working on a homework assignment where we are limited to using multi-dimensional arrays in order to create a program that finds two points nearest to each other in a three dimensional space. So far my code looks like this (hybridized from examples in my textbook and my own code):
package exercise7_7;
public class Exercise7_7 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of points:");
int numberOfPoints = input.nextInt();
double[][] points = new double[numberOfPoints][3];
System.out.println("Enter " + numberOfPoints + " points:");
for (int i = 0; i < points.length; i++) {
points[i][0] = input.nextDouble();
points[i][1] = input.nextDouble();
points[i][2] = input.nextDouble();
}
int p1 = 0, p2 = 1, p3 = 2;
double shortestDistance = distance(points[p1][0] , points[p1][1] , points[p1][2] ,
points[p2][0] , points[p2][1] , points[p2][2]);
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = distance(points[i][0] , points[j][0] , points[j][1] , points[j][2] , points[i][2] , points[j][2]);
if (shortestDistance > distance) {
p1 = i;
p2 = j;
shortestDistance = distance;
}
}
}
System.out.println("The closest two points are " + "(" + points[p1][0] + "," + points[p1][1] +
and (" + points[p2][0] + "," );
}
public static double distance(
double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) + ((z2 - z1) * (z2 - z1)));
}
}
What I mostly need help with is figuring out just how to get these points compared. I don't think the way I tackled this problem was the best way to do it.
Thanks for the help guys. I'm running on 2 hours of sleep for 2 days now so please excuse any stupid questions or sloppy code.
******
I think I've got it:
package exercise7_7;
public class Exercise7_7 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of points:");
int numberOfPoints = input.nextInt();
double[][] points = new double[numberOfPoints][3];
System.out.println("Enter " + numberOfPoints + " points:");
for (int i = 0; i < points.length; i++) {
points[i][0] = input.nextDouble();
points[i][1] = input.nextDouble();
points[i][2] = input.nextDouble();
}
int p1 = 0, p2 = 1;
double shortestDistance = distance(points[p1][0] , points[p1][1] , points[p1][2] ,
points[p2][0] , points[p2][1] , points[p2][2]);
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = distance(points[i][0] , points[j][0] , points[j][1] , points[j][2] , points[i][2] , points[j][2]);
if (shortestDistance > distance) {
p1 = i;
p2 = j;
shortestDistance = distance;
}
}
}
System.out.println("The closest two points are " + "(" + points[p1][0] + "," + points[p1][1] + "," + points[p1][2] +
") and (" + points[p2][0] + "," + points[p2][1] + "," + points[p2][2] + ")");
}
public static double distance(
double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) + ((z2 - z1) * (z2 - z1)));
}
}
Input is taken in, processed, and then outputs the two closest points. Just as a reference, when:
(-1,0,3),(-1,-1,-1),(4,1,1),(2,0.5,9),(3.5,1.5,3),(-1.5,4,2),(5.5,4,-0.5) are inputted, the outcome
seems to be (-1,0,3) and (4,1,1). Could someone confirm that for me.
If this isn't the way to follow up on my own question, I apologize. First day on these slopes and I'm still
learning the ropes.
Use a class to represent your points. This way to you have a distanceTo method that calculates and returns distance. Also you can have a toString method that prints out the point for display to the user. Taking your code rearranging yields this class:
public class ThreeDPoint {
final double x;
final double y;
final double z;
public ThreeDPoint(final double x, final double y, final double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double distanceto(final ThreeDPoint other) {
final double dx = other.x - x;
final double dy = other.y - y;
final double dz = other.z - z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
#Override
public String toString() {
return "{X=" + x + ",Y=" + y + ",Z=" + z + "}";
}
}
Now putting that together gives this, which is much more readable. I have removed the bit where you read points and used random numbers:
public static void main(String args[]) {
final ThreeDPoint[] points = new ThreeDPoint[5];
final Random random = new Random();
for (int i = 0; i < points.length; ++i) {
points[i] = new ThreeDPoint(random.nextInt(100), random.nextInt(100), random.nextInt(100));
}
//store min
double min = Double.POSITIVE_INFINITY;
int first = -1;
int last = -1;
for (int i = 0; i < points.length; ++i) {
for (int j = i + 1; j < points.length; ++j) {
final double d = points[i].distanceto(points[j]);
if (d < min) {
min = d;
first = i;
last = j;
}
}
}
System.out.println("The minimum distance is between point " + first + " and " + last + "(" + points[first] + " and " + points[last] + "). This distance is " + min + ".");
}
private static final class ThreeDPoint {
final double x;
final double y;
final double z;
public ThreeDPoint(final double x, final double y, final double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double distanceto(final ThreeDPoint other) {
final double dx = other.x - x;
final double dy = other.y - y;
final double dz = other.z - z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
#Override
public String toString() {
return "{X=" + x + ",Y=" + y + ",Z=" + z + "}";
}
}

Categories

Resources