I have a method that gets the area of a triangle, however it is returning 0.0.
public double getArea() {
//Find the length of sides
double side1 = p1.findLength(p2);
double side2 = p2.findLength(p3);
double side3 = p3.findLength(p1);
//Get area
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
My Point class with findLength(). This function works as intended in my testing:
public double findLength(Point another) {
return Math.sqrt(((another.getX() - this.getX()) * (another.getX() - this.getX()) )+
((another.getY() - this.getY()) * (another.getY() - this.getY())));
}
I can't seem to figure out why it isn't working.
Entire Point class:
/**
* Created by wilson on 9/8/2014.
*/
import java.math.*;
public class Point {
private double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double findLength(Point another) {
return Math.sqrt(((another.getX() - this.getX()) * (another.getX() - this.getX()) )+
((another.getY() - this.getY()) * (another.getY() - this.getY())));
}
}
My Test Program:
Point p1 = new Point(0,0);
Point p2 = new Point(3,3);
Point p3 = new Point(-3,-3);
Triangle2D t1 = new Triangle2D(p1, p2, p3);
System.out.println("Area of triangle: " + t1.getArea());
The "triangle" you tested:
Point p1 = new Point(0,0);
Point p2 = new Point(3,3);
Point p3 = new Point(-3,-3);
actually consists of three points all on the same line (the line x = y). Therefore, 0 is the correct answer. As far as I can tell, the code is correct.
Side note: I recommend using Math.hypot, which computes sqrt(x2 + y2) in the findLength function. Besides making findLength easier to read, it has the advantage that it won't overflow if x or y is so large that x2 or y2 won't fit in a floating-point number. (Not that it's likely you'll run into that problem, but why not do things right?)
Related
I have a simple class 2Dpoints with two fields, x and y. I want to write a code so that I could command one point to moves slowly to another point, like so that it moves on the vector line of their distances. But I don't know how?
I've first thought that it should contain a for loop so that it would know, it should move till it reaches the other point
something like for(int d=0 ; d<distance ; d++) but I don't know how should I then command it so that it would move on the line?
import java.lang.Math.*;
public class Punkt {
private int x;
private int y;
public Punkt(int x, int y) {
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int distance) {
x = x + distance;
}
public void setY(int distance) {
y = y + distance;
}
public void moveAbout(int dx, int dy) {
x = x + dx;
y = y + dy;
}
/// method for calculating the distance to another point
public double giveDistance(Punkt otherPoint) {
return Math.sqrt(
(otherPoint.getY() - y) *
(otherPoint.getY() - y) +
(otherPoint.getX() - x) *
(otherPoint.getX() - x));
}
}
I've commented the major lines:
import static java.lang.Math.*;
/**
* Immutable structure. Functional way
*/
class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Here you are. This is what you want to implement.
* from.moveTo(0.0, to) => from
* from.moveTo(1.0, to) => to
*
* #param by - from 0.0 to 1.0 (from 0% to 100%)
* #param target - move toward target by delta
*/
public Point moveTo(double by, Point target) {
Point delta = target.sub(this);
return add(delta.dot(by));
}
public Point add(Point point) {
return new Point(x + point.x, y + point.y);
}
public Point sub(Point point) {
return new Point(x - point.x, y - point.y);
}
public Point dot(double v) {
return new Point(v * x, v * y);
}
public double dist(Point point) {
return sub(point).len();
}
public double len() {
return sqrt(x * x + y * y);
}
public String toString() {
return x + ":" + y;
}
}
class Main {
public static void main(String[] args) {
Point source = new Point(2, 3);
Point target = new Point(-4, 9);
// You can utilize the cycle or implement kind of timer to animate something
for (int t = 0; t <= 100; t++) {
System.out.println(source.moveTo(0.01 * t, target));
}
}
}
https://replit.com/join/sucvdhpqoa-redneckz
#AlexanderAlexandrov I've change the type of my variables to double accordingly, now in one of my classes I have a method givePoints, which uses Scanner for asking a user how many points he wants and what are the coordinates then it saves them into an array of points with first element being always(0,0).
Another method takes an array of points as parameter and sort them in order of their distances to point(0,0).
These methods work perfectly. The problem is with method hitThepoints.
Here I want to first create the array of points, sort them, and then command my robot to hit all the points. robot is an object of class Robot extends circle, with position of type Point, that at first is at point(0,0)
public void hitThePoints(){
Point[] poi=sortPoints (givePoints()); //Creates a sorted array of points
Point short=new Point(poi[1].getX(),poi[1].getY());
System.out.println(" the nearest point is :");
System.out.println("("+short.getX()+ ","+short.getY()+")");
for(int i=1; i<poi.length;i++){
Point source=robot.position;
Point target=new Point(poi[i].getX(), poi[i].getY());
while(source.getX()!=target.getX() &&
source.getY()!=target.getY()){
robot.bewegeUm((source.moveTo(0.01,target)).getX(),
(source.moveTo(0.01,target)).getY());
if(source.getX()!=target.getX() &&
source.getY()!=target.getY()){break;}
System.out.println(source.getX() +","+ source.getY());
}
}
}
This is my test class,
public class Shape2DTester {
public static void main(String[] args) {
GeometricObject2D geoObject1 = new ComparableCircle2D(0, 5, 2);
GeometricObject2D geoObject3 = new ComparableCircle2D(0, 0, 2);
System.out.println("geoObject1 overlaps geoObject3: "
+ geoObject1.intersect(geoObject3));
}
}
This is my circle class,
public class ComparableCircle2D extends GeometricObject2D<ComparableCircle2D> {
public double x, y;
public double radius;
ComparableCircle2D() {
super();
this.radius = 1.0;
}
ComparableCircle2D(double radius) {
super();
this.radius = Math.abs(radius);
}
ComparableCircle2D(double x, double y, double radius) {
super(x, y);
this.radius = Math.abs(radius);
}
public double getArea() {
return Math.PI * getRadius() * getRadius();
}
public double getPerimeter() {
return 2 * Math.PI * getRadius();
}
public void setRadius(double setRadius) {
this.radius = Math.abs(setRadius);
}
public double getRadius() {
return radius;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public boolean intersect(GeometricObject2D g) {
ComparableCircle2D other = (ComparableCircle2D) g;
double dx = other.x - getX();
double dy = other.y - getY();
double radi = other.radius + getRadius();
return (dx * dx + dy * dy < radi * radi);
}
}
}
this is my superclass,
public abstract class GeometricObject2D<T extends GeometricObject2D> implements
Comparable<GeometricObject2D> {
public double x, y;
GeometricObject2D() {
this.x = 0;
this.y = 0;
}
GeometricObject2D(double x, double y) {
this.x = x;
this.y = y;
}
public abstract double getArea();
public abstract double getPerimeter();
public abstract boolean intersect(GeometricObject2D g);
#Override
public int compareTo(GeometricObject2D o) {
// TODO Auto-generated method stub
return 0;
}
}
I want to find out possibility of intersecting two circles but there is an error in my code that I didn't realize.
For example I create two circle object coordinates-1(0,0) , radius-1=2 and coordinates-2(0,5) ,radius-2=2. That above method must return false but returns true. I didn't find error.
System.out.println("geoObject1 intersects geoObject3: "
+ geoObject1.intersect(geoObject3));
prints geoObject1 intersects geoObject3: true
As #Pshemo said, your code (now that you've shown it) has an extra } at the end that shouldn't be there.
How, if we paste all that code into IDEONE, and run it, we confirm your error.
If we then DEBUG the code by adding a single print statement, we see:
dx=0.0, dy=0.0, radi=4.0
Hmmm, why is dy = 0 when it should be 5?
Answer: Because you added another set of x and y fields to your subclass, that is hiding the fields from the base class!!!!
Simple debugging would have shown you this yourself. This is what #PeterLawrey was talking about in his comment:
you mistake is it is likely to be; the values are not what you think they are. This is where debugging your code can show this.
Of course, if you had used a good IDE, you wouldn't even need to debug, because the IDE would have warned you about the field hiding.
Rather than Math.pow(x, 2) it is more efficient to do x * x, and instead of using Math.sqrt you can square the sum of the radii.
public boolean intersect(GeometricObject2D g) {
ComparableCircle2D other = (ComparableCircle2D) g;
double dx = other.x - x; // e.g. 0 - 0
double dy = other.y - y; // e.g. 5 - 0
double radii = other.radius + radius; // e.g. 2 + 2
return dx * dx + dy * dy < radii * radii ; // e.g. 0 + 25 < 16 is false.
}
You never assign the fields x and y. Therefore dx = dy = 0.
You have to either assign the field's values or use the fields in the superclass (but you shouldn't have fields with the same information in the same object, so remove the fields created in ComparableCircle2D).
Also if your circle is defined as contour, not as area, then the test for intercepting circles is incorrect. Consider the case where 2 circles with the same center have different radii: dx² + dy² = 0 < dr², but the contours don't intersect; only the areas inside the circles overlap.
What do I do wrong? I get incorrect results (coordinates).
A triangle (see the picture below: blue is the original triangle, lime is the rotated one: a clone. Edge A is a fixed point).
The classes I use:
A Point class:
public class Point {
private final double x;
private final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
#Override
public String toString() {
return "[(" + x + ") (" + y + ")]";
}
}
An abstract Object2D class:
public abstract class Object2D {
Point[] point;
public Point getPoint(int i) {
return point[i];
}
public double getLowestX() {
return Arrays.asList(point).stream()
.mapToDouble(Point::getX)
.min().getAsDouble();
}
public double getHighestX() {
return Arrays.asList(point).stream()
.mapToDouble(Point::getX)
.max().getAsDouble();
}
public double getLowestY() {
return Arrays.asList(point).stream()
.mapToDouble(Point::getY)
.min().getAsDouble();
}
public double getHighestY() {
return Arrays.asList(point).stream()
.mapToDouble(Point::getY)
.max().getAsDouble();
}
public double getLength() {
return getSide(getLowestX(), getHighestX());
}
public double getHeight() {
return getSide(getLowestY(), getHighestY());
}
private double getSide(double v1, double v2) {
return (v1 < v2) ? (0 - v1) + v2 : (0 - v2) + v1;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Point pt : point) sb.append(pt).append("\n");
return sb.toString();
}
}
A Line class:
public class Line extends Object2D {
public Line(Point point0, Point point1) {
point = new Point[2];
point[0] = point0;
point[1] = point1;
}
public double getLineLength() {
return Math.sqrt(Math.pow(getLength(), 2) + Math.pow(getHeight(), 2));
}
}
My Triangle class:
public class Triangle extends Object2D {
public Triangle(Point point0, Point point1, Point point2) {
point = new Point[3];
point[0] = point0;
point[1] = point1;
point[2] = point2;
}
public static Triangle getRotatedTriangle(Triangle triangle) {
Point point0 = triangle.getPoint(0);
Point point1 = triangle.getPoint(1);
Point point2 = triangle.getPoint(2);
Line baseLine = new Line(point0, point1);
double rotationHeight = baseLine.getHeight();
double baseLength = baseLine.getLineLength();
double sinA = rotationHeight / baseLength;
double angle = Math.asin(sinA);
double cosA = Math.cos(angle);
point1 = new Point(
(point1.getX() * cosA - point1.getY() * sinA),
(point1.getX() * sinA + point1.getY() * cosA));
point2 = new Point(
(point2.getX() * cosA - point2.getY() * sinA),
(point2.getX() * sinA + point2.getY() * cosA));
return new Triangle(point0, point1, point2);
}
}
And, of course, my main class:
public class TestDrive {
public static void main(String[] args) {
Triangle triangle = new Triangle (
new Point(-6.5, -1.5),
new Point(2.5, 7.5),
new Point(6.5, -5.5)
);
System.out.println(triangle);
System.out.println(Triangle.getRotatedTriangle(triangle));
}
}
You made 2 mistakes in your code:
You are trying to rotate with the angle α when you should be rotating with the angle -α (since you are rotating clockwise).
Your multiplication matrix is incorrect: your code will perform a rotation around the origin of the XY plane instead of rotating around the point A. For the point (x, y) rotated by the rotation matrix R around the center (a, b), the correct formula for the new rotated point (x', y') would be (x', y') = R * (x - a, y - b) + (a, b).
This should be enough for you to correct your code. As reference, here's the solution I get for the rotated triangle:
[(-6.5) (-1.5)]
[(6.227922061357855) (-1.5000000000000009)]
[(-0.1360389693210724) (-13.520815280171309)]
I have the code for circle-circle intersection. But I need to expand it to 3-D. Could you please help me to write the functions?
static class Point{
double x, y, z;
int dimension;
Point(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
dimension = 3;
}
Point sub(Point p2) {
return new Point(x - p2.x, y - p2.y, z - p2.z);
}
Point add(Point p2) {
return new Point(x + p2.x, y + p2.y, z + p2.z);
}
double distance(Point p2) {
return Math.sqrt((x - p2.x)*(x - p2.x) + (y - p2.y)*(y - p2.y) + (z - p2.z)*(z - p2.z));
}
Point normal() {
double length = Math.sqrt(x*x + y*y + z*z);
return new Point(x/length, y/length, z/length);
}
Point scale(double s) {
return new Point(x*s, y*s, z*s);
}
double[] array()
{
return new double[]{x,y,z};
}
}
static class Circle {
double x, y, r, left;
Circle(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
left = x - r;
}
Circle(double[] c, double r) {
this(c[0], c[1], r);
}
Circle(Point c, double r)
{
this(c.x, c.y, r);
}
Point[] intersections(Circle c)
{
Point P0 = new Point(x, y,0);
Point P1 = new Point(c.x, c.y,0);
double d, a, h;
d = P0.distance(P1);
a = (r*r - c.r*c.r + d*d)/(2*d);
h = Math.sqrt(r*r - a*a);
if(Double.isNaN(h))
return null;
Point P2 = P1.sub(P0).scale(a/d).add(P0);
double x3, y3, x4, y4;
x3 = P2.x + h*(P1.y - P0.y)/d;
y3 = P2.y - h*(P1.x - P0.x)/d;
x4 = P2.x - h*(P1.y - P0.y)/d;
y4 = P2.y + h*(P1.x - P0.x)/d;
return new Point[]{new Point(x3, y3, 0), new Point(x4, y4, 0)};
}
}
static class Sphere
{
double x,y,z,r,left;
Sphere(double x, double y, double z, double r)
{
this.x = x;
this.y = y;
this.z = z;
this.r = r;
left = x-r;
}
Circle intersection(Sphere s)
{
Point P0 = new Point(x, y, z);
Point P1 = new Point(s.x, s.y, s.z);
double d, a, h;
d = P0.distance(P1);
a = (r*r - s.r*s.r + d*d)/(2*d);
h = Math.sqrt(r*r - a*a);
if(Double.isNaN(h))
return null;
Point P2 = P1.sub(P0).scale(a/d).add(P0);
return new Circle(P2, h);
}
Point[] intersections(Circle c)
{
Point P0 = new Point(0,0,0);
Point P1 = new Point(0,0,0);
//...
return new Point[]{P0, P1};
}
}
I have checked this link and this link, but I could not understand the logic behind them and how to code them.
I tried ProGAL library for sphere-sphere-sphere intersection, but the resulting coordinates are rounded. I need precise results.
To be sure , what you need is how to intersect 3 spheres?
if so , your current data structure for circle is useless.
let say you want to intersect 3 spheres : s1 , s2 , s3, intersection of s1 and s2 will be a circle that you will intersect with s3 for final results, BUT keep it mind that the circle is not on XoY plane , it's center may be on any 3D coordinate and it will face a direction in the 3D space. to store information of such a circle you need , centerX , centerY , centerZ , radius and a 3d vector called normal.
class Circle3D
{
Point center;
double r;
Point normal;
...
}
after you completed this new class, you can use it to store information about Sphere-Sphere intersection. after that you must implement Sphere-Circle3D intersection:
Circle3D Intersect(Sphere s1 , Sphere s2)
{
double d = dist(s1.center , center)
double x = (d*d + s1.r*s1.r - s2.r*s2.r)/(2*d)
Point normal = normalize(s2.Center - s1.Center)
Point center = s1.center + x*normal;
double radius = sqrt(s1.r*s1.r - x*x)
return new Circle3D(center , radius , normal);
}
don't panic if math seems chaotic , read this Page
now it is timee ofr sphere-circle3D intersection, for that:
point[] Intersect(Sphere s , Circle3D c)
{
/*
first we check if sphere even intersects with plane of c
I assume you know how to implement some if these functions
*/
if(GetDistanceOfPointFromPlane(s.center , new Plane(c.center , normal))>s.radius)
return NULL;
/*
again we check possibility of avoiding math of intersection
*/
point dir = Normalize(s.center - c.center);
if(!DoesRayIntersectWithSphere(s , new Ray(c.center , c.radius*dir)))
return NULL;
/*
this is the ugly part of code that unfortunately is deep trig math.
you must describe sphere and circle equations in polar system , then
you must solve sphere = circle
I hope the link below be helpful
*/
}
here is the link mentioned in cemments above
http://mathworld.wolfram.com/SphericalCoordinates.html
I'm Suppoused to write a class with a constructor for a Point and a Line and in the Line class I'm suppoused to write a method that finds if two lines intersect or not. This is my Point class:
public class Point {
static double x;
static double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
This is my Line Class
public class Line {
public Line(Point x, Point y) {
}
// create two points for a line
static Point x1y1;
static Point x2y2;
// create another two points for another line
static Point x3y3;
static Point x4y4;
public static void main(String[] args) {
// create lines
Line line1 = new Line(x1y1, x2y2);
Line line2 = new Line(x3y3, x4y4);
//initialize points
x1y1 = new Point(1.0, 1.0);
x2y2 = new Point(3.0, 3.0);
x3y3 = new Point(1.0, 2.0);
x4y4 = new Point(4.0, 2.0);
//call method to find if lines intersect
findIntersection(line1, line2);
System.out.println(x1y1.x);
}
public static void findIntersection(Line line1, Line line2) {
double denominator = (x1y1.x - x2y2.x) * (x3y3.y - x4y4.y)
- (x1y1.y - x2y2.y) * (x3y3.x - x4y4.x);
double px = 0;
double py = 0;
if (denominator == 0) {
System.out.println("Lines are parallel, they do not intersect");
} else {
px = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.x - x4y4.x) - (x1y1.x - x2y2.x)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
py = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.y - x4y4.y) - (x1y1.y - x2y2.y)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
System.out.println(px + "," + py);
}
}
}
The problem is I initialize all the points so that the lines should intersect, but when I try to print out the values of the points, the values of the x-es and y-s of the firss 3 points are equal to the 4th one although I'm initializing them with different values and thus the method calcutes that the lines do not intersect. Why are the values of the first three y and x equal to the 4th?
It's because x and y of Point class are static. It means, every instance of Point class will use the same values. Remove static to fix it.
public class Point {
double x;
double y;
You should improve the class design too anyway: Two classes (Point, Lines) another with main method.
The same for Line too. Or you will end up with the same Points for every line. (You avoited this using 4 variables i think.)
Something like this
public class Point {
double x;
double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
public class Line {
Point a;
Point b;
public Line(Point a, Point b) {
this.a = a;
this.b = b;
}
public Point itIntersect(Line line) {
// here change the logic
Point point = null;
double denominator = (x1y1.x - x2y2.x) * (x3y3.y - x4y4.y)
- (x1y1.y - x2y2.y) * (x3y3.x - x4y4.x);
double px = 0;
double py = 0;
if (denominator != 0) {
px = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.x - x4y4.x) - (x1y1.x - x2y2.x)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
py = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.y - x4y4.y) - (x1y1.y - x2y2.y)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
// System.out.println(px + "," + py);
point = new Point(px, py);
}
return point;
}
}
P.S I didn't changed the logic of intersect because it's too long, but you could do something like this to improve the design.
Then you need to do Point point = line.itIntersect(anotherLine);
If it's null it don't intersect, else it will return the point.
P.S Make x and y private, i didn't because it was an example.