It's been difficult to Google for a solution, because I'm not interested in the vector data strucutre. I'm interested in the phytsics vector. I'm trying to create a generic class to wrap any number type for a Vector. This is my original double vector:
public class Vector2D {
private double x, y;
Vector2D (double x, double y){
this.x = x;
this.y = y;
}
public static Vector2D random() {
return new Vector2D(Math.random() * 2 - 1, Math.random() * 2 - 1);
}
public double magnitude(){
return Math.sqrt(this.x * this.x + this.y * this.y);
}
public Vector2D add(Vector2D other) {
return new Vector2D(this.x + other.x, this.y + other.y);
}
//etc...
}
However, I'm coming across some dificulites in porting this to a generic class. This is what I have so far:
public class Vector2D<T extends Number> {
private T x, y;
Vector2D (T x, T y){
this.x = x;
this.y = y;
}
public static Vector2D random() {
return new Vector2D(Math.random() * 2 - 1, Math.random() * 2 - 1);
}
public T magnitude(){
//this gives an error: cannot cast from double to T
return (T)Math.sqrt(this.x.doubleValue() * this.x.doubleValue() + this.y.doubleValue() * this.y.doubleValue());
}
}
I'm stuck on magnitude and random. I'm really stumped. Any guidance as to how I can complete those methods?
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());
}
}
}
I have a work about calculating the distances between two points. It consist of Point Class, Line Class as well as Main Class. The following is my Point class. After working on the private double distance(Point p) method, I am unable to return p at the public double getDistance(Point p) method. I run code on Command Prompt and it shows error: incompatible types: Point cannot be converted to double. Please advice.
class Point
{
private int x;
private int y;
//Constructor
public Point()
{
//nothing
}
//Second constructor
public Point (int x, int y)
{
this.x = x;
this.y = y;
}
//Copy constructor
public Point (Point p)
{
this (p.x, p.y);
}
private double distance(Point p)
{
int dX = this.x - p.x;
int dY = this.y - p.y;
double result = Math.sqrt(dX * dX + dY * dY);
return result;
}
public double getDistance(Point p)
{
return p;
}
//getter
public int getX()
{
return x;
}
public int getY()
{
return y;
}
//setter
public void set(int x, int y)
{
this.x = x;
this.y = y;
}
public String toString ()
{
return String.format ("Given Point (%d, %d)", x, y);
}
}
You have the object Point p as your parameter and return it as a double.
In your block of code you're stating a return of the Object Point p and not a double data type.
public double getDistance(Point p) {
return p;
}
If you're just trying to calculate the distance of the object, use your distance() method. This method already returns the distance calculated as a double.
private double distance(Point p) {
int dX = this.x - p.x;
int dY = this.y - p.y;
double result = Math.sqrt(dX * dX + dY * dY);
return result;
}
I'm stuck on this question for a couple of days now and would really like to get some help.
I am given a 2 dimensional point in the range of (0-1 not including 1), such as (0.5,0.2), and N other points (also in the range of 0-1).
The first part of the question is to implement the "dumb" algorithm, which when given a certain point will find the point with the shortest distance from it, which has a complexity of O(N).
The part I'm stuck at, requires to build a Matrix K on K, where each "cell" will contain the points that belong to that cell. Once done, when given the original point I will need to search for the point with the shortest distance to it only in some of the cells and not the entire Matrix, which should result better complexity.
My original thought is to devide the points so that each block will have an arraylist of points that belong to him, and then to somehow go through the main block(the one that the original point belongs to) and continue by going through it's neighbors, however implementing it hasn't been very successful.
I would highly appreciate any help/ advice.
Below is what I currently have:
public class Point {
private double x;
private double y;
private Block b;
public Point(double x, double y)
{
this.x=x;
this.y=y;
}
public Point(double x, double y, Block b) //consrtuctor for complex case
{
this.x=x;
this.y=y;
b.points.add(this);
}
public double getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public double distance(Point p)
{
double res=0;
res = Math.sqrt(Math.pow(this.x-p.getX(),2)+Math.pow(this.y-p.getY(),2));
return res;
}
}
import java.util.ArrayList;
public class Block {
private int x;
private int y;
public ArrayList<Point> points;
public Block(int x, int y) {
points = new ArrayList<Point>();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
import java.util.Random;
public class ComplexCase {
private Block[][] blockMat;
public ComplexCase(int k, int n)
{
Random generator = new Random();
Point p1;
Block b1;
double x,y;
int bx1,by1;
int t;
t = 1/k;
blockMat = new Block[k][k];
for (int i =0;i<n;i++)
{
x = generator.nextDouble();
y = generator.nextDouble();
bx1 = (int) (x/t);
by1 = (int) (y/t);
b1 = new Block(bx1,by1);
p1 = new Point(x,y,b1);
}
}
public Block[][] getBlockMat() {
return blockMat;
}
public void setBlockMat(Block[][] blockMat) {
this.blockMat = blockMat;
}
}
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.
I wrote this Java class for doing rotational transforms about the x,y,z axes.
public class Coord {
private double x,y,z;
public Coord(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Coord M(Coord[] M) {
return new Coord(
x*M[0].x + y*M[0].y + z*M[0].z,
x*M[1].x + y*M[1].y + z*M[1].z,
x*M[2].x + y*M[2].y + z*M[2].z);
}
public Coord xR(double theta) {
double s = Math.sin(theta);
double c = Math.cos(theta);
return M(new Coord[]{V(1,0,0), V(0,c,-s), V(0,s,c)});
}
public Coord yR(double theta) {
double s = Math.sin(theta);
double c = Math.cos(theta);
return M(new Coord[]{V(c,0,s), V(0,1,0), V(-s,0,c)});
}
public Coord zR(double theta) {
double s = Math.sin(theta);
double c = Math.cos(theta);
return M(new Coord[]{V(c,-s,0), V(s,c,0), V(0,0,1)});
}
public Coord V(double x, double y, double z) {
return new Coord(x,y,z);
}
}
It transforms a x,y,z coordinate, as given by the class Coord, to a new coord by the matrix multiplication M. It works OK, such as Coord c = new Coord(1,1,0).xR(0.1);, try System.out.printf("%f,%f,%f", c.x, c.y, c.z); will show a small rotation (theta=0.1 radians) about x, while keeping x constant.
Anyway, I want to know if there's any way of getting rid of all the Math.sin, Math.cos while still maintaining readability (preferably) - but just getting rid of them would be good!. They are annoying to look at, and, seem to be asking to be reduced somehow
As per Paul's comment, turns out to be pretty good
import static java.lang.Math.sin;
import static java.lang.Math.cos;
public class Coord {
private double x,y,z;
public Coord(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Coord M(Coord[] M) {
return new Coord(
x*M[0].x + y*M[0].y + z*M[0].z,
x*M[1].x + y*M[1].y + z*M[1].z,
x*M[2].x + y*M[2].y + z*M[2].z);
}
public Coord xR(double t) {
return M(new Coord[]{V(1,0,0), V(0,cos(t),-sin(t)), V(0,sin(t),cos(t))});
}
public Coord yR(double t) {
return M(new Coord[]{V(cos(t),0,sin(t)), V(0,1,0), V(-sin(t),0,cos(t))});
}
public Coord zR(double t) {
return M(new Coord[]{V(cos(t),-sin(t),0), V(sin(t),cos(t),0), V(0,0,1)});
}
public Coord V(double x, double y, double z) {
return new Coord(x,y,z);
}
}
Answering my own Q .. happy to know of other ways, looks pretty syntax bare now though .... I think I can live with this