SIMD Vectors/Matrices in Java? - java

I'm writing a graphics library in Java, primarily for use in game development. It needs basic vector and matrix objects for use in 3D calculations, and ideally those objects would employ SIMD operations. Although Java doesn't provide such operations directly, it is possible to hint to the JVM to use them in the context of large arrays. Hence...
Can the JVM vectorize operations on vector-like objects? If so, how can I ensure that this happens?
To clarify: I need operations on small, statically sized objects, not variable-length arrays. E.g., matrices that are strictly 3x3 or 4x4, vectors that are strictly of length 4, etc. Vectorization of large, variable-length arrays has already been discussed.
Some example candidates for vectorization:
public class Vector4f
{
public int x, y, z, w;
public void madd(Vector4f multiplicand, Vector4f addend)
{
this.x = this.x * multiplicand.x + addend.x;
this.y = this.y * multiplicand.y + addend.y;
this.z = this.z * multiplicand.z + addend.z;
this.w = this.w * multiplicand.w + addend.w;
}
public float dot(Vector4f other)
{
return this.x * other.x
+ this.y * other.y
+ this.z * other.z
+ this.w * other.w;
}
}
public class Matrix44f
{
public float m00, m01, m02, m03;
public float m10, m11, m12, m13;
public float m20, m21, m22, m23;
public float m30, m31, m32, m33;
public void multiply(Matrix44f other) { ... }
public void transform(Vector4f other) { ... }
public void andSoOnAndSoForth() { ... }
}

Related

call a method in class, inheritance

I have a problem, the solution is probably very easy, but nothing comes to mind at the moment, so I am looking for a little help.
... so I have a problem with calling the method.
I have a Space 2D class:
public class Space2D {
//several other methods etc.
//for example I will take this method
public double distance(Space2D p1, Space2D p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
and I want to call it in the SpaceTest class:
public class SpaceTest extends Space3D {
public static void main(String[] args) {
Space2D point2D = new Space2D();
// I also have a Space 3D class that inherits from the 2D class.
// but I want to call the distance method from the Space 2D class so I'll try to do it like this:
point2D.distance(3,4) // <-- wrong
}
}
I would like to put 3 and 4 after p1 and p2 from the distance method but I get a bug that I have to put integers in it if I want to do so, so my question what do I have to put in calling this method so that I can run it, i.e. what do I have to put for this object ?? "Space2D p1"?
point2D.distance (???)
Thank you in advance for your help and explanation, I hope you will help me understand this.
public double distance(Space2D p1, Space2D p2) {
...
This means when you invoke distance you have to pass in two objects of type Space2D.
point2D.distance(3,4) <-- wrong
You tried to invoke it with two integers, which is why you get the error. Points have an x and y coordinate, what does it even mean to ask for the distance between 3 and 4 if the domain is R2.
What you probably want is something like
int dist = point2d.distance(new Point2D(3,0), new Point2D(4,0));
That's because you're putting integers as parameter which is not allowing to take as parameter. Distance function takes distance(Space2D p1, Space2D p2) Space2D object.
You can use like this:
In Space2D Class :
public class Space2D {
private int x;
private int y;
public Space2D(int x, int y) {
this.x = x;
this.y = y;
}
//several other methods etc.
//for example I will take this method
public static double distance(Space2D p1, Space2D p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
In SpaceTest class :
public class SpaceTest extends Space3D {
public static void main(String[] args) {
Space2D.distance(new Space2D(3, 2), new Space2D(3, 2));
}
}

How to make a class operate with math operation in java? [duplicate]

This question already has answers here:
Operator overloading in Java
(10 answers)
Closed 5 years ago.
I have the following class, which describe one point on XY surface:
class Point{
double x;
double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
So I want to overlad + and - operators to have possibility write run following code:
Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Point resAdd = p1 + p2; // answer (4, 6)
Point resSub = p1 - p2; // answer (-2, -2)
How can I do it in Java? Or I should use methods like this:
public Point Add(Point p1, Point p2){
return new Point(p1.x + p2.x, p1.y + p2.y);
}
Thanks in advance!
You cannot do this in Java. You'd have to implement a plus or add method in your Point class.
class Point{
public double x;
public double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public Point add(Point other){
this.x += other.x;
this.y += other.y;
return this;
}
}
usage
Point a = new Point(1,1);
Point b = new Point(2,2);
a.add(b); //=> (3,3)
// because method returns point, you can chain `add` calls
// e.g., a.add(b).add(c)
Despite you can't do it in pure java you can do it using java-oo compiler plugin.
You need to write add method for + operator:
public Point add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
and java-oo plugin just desugar operators to these method calls.
There is no operator overloading in Java. Apparently for reasons of taste. Pity really.
(Some people will claim that Java does have overloading, because of + with String and perhaps autoboxing/unboxing.)
Let's talk about value types.
Many early classes (and some later ones) make a right mess of this. Particularly in AWT. In AWT you should be explicitly making copies of simple values all over the place. Almost certainly you want to make value types immutable - the class should be final and it should never change state (generally all final fields pointing to effective immutables).
So:
public final class Point {
private final int x;
private final int y;
private Point(int x, int y) {
this.x = x;
this.y = y;
}
public static of(int x, int y) {
return new Point(x, y);
}
public int x() {
return x;
}
public int y() {
return y;
}
public Point add(Point other) {
return of(x+other.x, y+other.y);
}
// Standard fluffy bits:
#Override public int hashCode() {
return x + 37*y;
}
#Override public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point)obj;
return x==other.x && y==other.y;
}
#Override public String toString() {
return "("+x+", "+y+")";
}
}
The original code was confused between int and double, so I've chosen one. If you used double you should exclude NaN. "Point" tends to imply an absolute point, which doesn't make sense to add. "Vector" or "dimension" would probably be more appropriate, depending upon what you intend.
I've hidden the constructor, as identity is not important. Possibly values could be cached. Possibly it is, say, common to add a point to a zero point, so no points need to be created.
It's possible you might want a mutable version, for example to use as an accumulator. This should be a separate class without an inheritance relationship. Probably not in simple cases, but I'll show it anyway:
public final class PointBuilder {
private int x;
private int y;
public PointBuilder() {
}
public PointBuilder(Point point) {
this.x = point.x;
this.y = point.y;
}
public Point toPoint() {
return new Point(x, y);
}
public PointBuilder x(int x) {
this.x = x;
return this;
}
public PointBuilder y(int y) {
this.y = y;
return this;
}
public PointBuilder add(Point other) {
this.x += other.x;
this.y += other.y;
return this;
}
}
You cannot do this in Java because there is no operator overloading in Java.
You have to use the second option you have mentioned:
Edit: You can add the Add method in the Point class itself
public Point Add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
You cannot overload operators in java. You will need handle this in Point class.
You cannot override operators in Java. That's one of the reasons why any nontrival math (especially geometric) operations should not be implemented in Java (the Point class above is kind of such a class, if you want it to do some real work, for example a line-line intersection, you'd better do it in C++).

How can I print multiple class instances in one statement? Java

public Class Point{
private double x;
private double y;
public Point() {
super();
}
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
public static Point deepCopy(Point p2) {
Point point2 = new Point(p2.x+2, p2.y+2);
return point2;
}
public static Point shallowCopy(Point p4){
return p4;
}
public void setPoint3X(double x3) {
this.x = x+1;
}
public void setPoint3Y(double y3) {
this.y = y+1;
}
public void setPoint2(double x2, double y2) {
this.x = x2+2;
this.y = y2+2;
}
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 String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
public class PointDemo {
public static void main(String[] args) {
double x = 0;
double y = 0;
Point point1 = new Point(5, 10);
Point point2 = Point.deepCopy(point1);
Point point3 = Point.deepCopy(point2);
point3.setPoint3X(x);
point3.setPoint3Y(y);
Point point4 = new Point();
point4 = Point.shallowCopy(point3);
Question 4 -
Write a class called Point. The class has two instance fields: x and y, both are of double type.
Write two constructors: one that uses x and y values for a point, and the other uses the first point values to create a second Point object with the exact same x and y values. Write a Demo class to build the following four Point objects.
Point 1: (x=5, y=10)
Point 2: (x=7, x=12). This point needs to be built using the deep copy constructor that copies point 1 and then using only one setter method.
Point 3: (x=10, y=15). This point needs to be built using the deep copy method that uses Point 2 as the original and then using two setter methods to change the required x and y values.
Point 4: This point needs to be built using the shallow copy method and it must use Point 3 as the shallow copy template.
Finally print all four points using one statement.
Okay. So my code gives me all the values from point1-point4 however, I cannot figure out a way to print them all in one statement. Obviously a loop in the demo class can print every Point object but that would be multiple print statements which violates the one print statement requirement.
Also, I cannot use an array in the Point class because it violates the 2 fields requirement.
Can anybody help or give me a suggestion as to how I can take all the Point objects and print it in one statement? Or is that even possible and maybe I am reading the question wrong?
You can use PrintStream.format(format(String format, Object... args):
System.out.format("(%f, %f), (%f, %f), (%f, %f), (%f, %f)\n", point1.x, point1.y, point2.x, point2.y, ...and so on);
I'm going to post this as an answer too since I think it might be what your instructor actually wants.
The key point here is to remember that the toString() method on your class can be used like a regular string and concatenate other strings, and that's what you normally do with + when calling println(). So just use the normal println() method like you've probably been doing already.
System.out.println( "Point 1 - " + point1.toString() + ";\n"
+ "Point 2 - " + point2.toString() + ";\n"
+ "Point 3 - " + point3.toString() + ";\n"
+ "Point 4 - " + point4.toString() + ";" );
You can use streams:
Arrays.stream(new Point[] {point1, point2, point3, point4}).forEach(System.out::println);
or String.format()
System.out::println(String.format("%s %s %s %s", point1, point2, point3, point4));

What type collection use for sorted unique object in Java?

I have simple object:
public class Vector3i {
public int x, y, z;
public Vector3i(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
}
What collection I need for sorted unique items?
Thank you for your help and advice.
To sort unique object in java you're going to want to create you're own comparator.
Using comparator to make custom sort

Loss of precision calculating degrees from two points

I have made a class Location which allows to set, change a location (coordinates x,y , the limits are decided by xMin,xMax,yMin,yMax), to caluculate the distance between two points, and to get the direction from another location.
The direction is in degress (in [0,2pi]) from another location.
The direction goes from North (assuming that North is the pole oriented where there are higher coordinates), in clockwise order.
package TruckingCompany;
public class Location
{
private double x;
private double y;
private static final double xMax=1000.0;
private static final double xMin=-1000.0;
private static final double yMax=1000.0;
private static final double yMin=-1000.0;
public Location()
{
setX(0.0);
setY(0.0);
}
public Location(double x,double y)
{
setX(x);
setY(y);
}
public Location(Location location)
{
setX(location.getX());
setY(location.getY());
}
public void setX(double x)
{
if(x>=xMin && x<=xMax)
this.x=x;
}
public void setY(double y)
{
if(y>=yMin && y<=yMax)
this.y=y;
}
public void set(double x,double y)
{
setX(x);
setY(y);
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public double getDistanceFrom(Location from)
{
double dx,dy;
dx=from.getX()-x;
dy=from.getY()-y;
return Math.sqrt(Math.pow(dx, 2.0)+Math.pow(dy, 2.0));
}
public double getDirectionFrom(Location from)
{
double dy=from.getY()-y;
double direction=Math.PI/4 - Math.asin (Math.toRadians(dy/getDistanceFrom(from)));
if(Double.isNaN(direction)==false)
{
if(from.getX()-x<0.0)
direction+=Math.PI/2;
if(dy<0.0)
direction+=Math.PI;
}
return direction;
}
#Override
public String toString()
{
return "(" + x + " , " + y + ")";
}
}
The problem is the the precision, for example I try to calculate the distance from these two locations:
Location l1,l2;
l1=new Location(0.0,0.0);
l2=new Location(300.0,300.0);
System.out.print(Math.toDegrees(l1.getDirectionFrom(l2)));
The problem is the precision: in this example it prints 44.29 degrees, it should be 45.0, why a so huge loss of precision?
You're near 45 degrees, which means you're going to be operating close to maxima and minima for some trig functions. I'd check the steps and see if you're getting an intermediate result very close to 0.
Try replacing the call to pow with dx*dx and dy*dy.
Break this up with intermediate results.
Use Math.atan2(deltaX, deltaY) to calculate the angle of a vector in radians. It returns answers all the way from 0 to 2 * Math.PI without having to do casework depending on the signs of the inputs.

Categories

Resources