1 package net.sf.openrocket.optimization.general;
3 import java.util.Arrays;
5 import net.sf.openrocket.util.MathUtil;
8 * An immutable n-dimensional coordinate point.
10 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
12 public final class Point {
14 private final double[] point;
15 private double length = -1;
16 private double length2 = -1;
19 public Point(int dim) {
21 throw new IllegalArgumentException("Invalid dimensionality " + dim);
23 point = new double[dim];
26 public Point(int dim, double value) {
28 Arrays.fill(point, value);
31 public Point(double... value) {
32 if (value.length == 0) {
33 throw new IllegalArgumentException("Zero-dimensional point not allowed");
35 point = value.clone();
38 private Point(Point p) {
39 point = p.point.clone();
45 * Return the point dimensionality.
47 * @return the point dimensionality
55 public double get(int i) {
59 public Point set(int i, double v) {
60 Point p = new Point(this);
67 * Return a new point that is the sum of two points.
69 * @param other the point to add to this point.
70 * @return the sum of these points.
72 public Point add(Point other) {
73 Point p = new Point(this);
74 for (int i = 0; i < point.length; i++) {
75 p.point[i] += other.point[i];
82 * Return a new point that is the subtraction of two points.
84 * @param other the point to subtract from this point.
85 * @return the value of this - other.
87 public Point sub(Point other) {
88 Point p = new Point(this);
89 for (int i = 0; i < point.length; i++) {
90 p.point[i] -= other.point[i];
97 * Return this point multiplied by a scalar value.
99 * @param v the scalar to multiply with
100 * @return the scaled point
102 public Point mul(double v) {
103 Point p = new Point(this);
104 for (int i = 0; i < point.length; i++) {
112 * Return the length of this coordinate.
114 * @return the length.
116 public double length() {
118 length = Math.sqrt(length2());
125 * Return the squared length of this coordinate.
127 * @return the square of the length of thie coordinate.
129 public double length2() {
132 for (double p : point) {
141 * Return the point as an array.
143 * @return the point as an array.
145 public double[] asArray() {
146 return point.clone();
150 public boolean equals(Object obj) {
154 if (!(obj instanceof Point))
157 Point other = (Point) obj;
158 if (this.point.length != other.point.length)
161 for (int i = 0; i < point.length; i++) {
162 if (!MathUtil.equals(this.point[i], other.point[i]))
169 public int hashCode() {
171 for (double d : point) {
173 n += (int) (d * 1000);
179 public String toString() {
180 return "Point" + Arrays.toString(point);