From 03e2fc959702e7654c507c4c6125ea1c1b54ecb6 Mon Sep 17 00:00:00 2001 From: Benjamin Culkin Date: Mon, 5 Feb 2018 13:01:44 -0800 Subject: Add dual numbers Dual numbers are a easy way of doing automatic numeric differentiation of expressions. --- base/src/main/java/bjc/utils/math/Dual.java | 83 +++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 base/src/main/java/bjc/utils/math/Dual.java (limited to 'base/src/main/java/bjc/utils/math/Dual.java') diff --git a/base/src/main/java/bjc/utils/math/Dual.java b/base/src/main/java/bjc/utils/math/Dual.java new file mode 100644 index 0000000..53ddc32 --- /dev/null +++ b/base/src/main/java/bjc/utils/math/Dual.java @@ -0,0 +1,83 @@ +package bjc.utils.math; + +/** + * Represents a 'dual' number. + * + * Think imaginary numbers, where instead of i, we add a value d such that d^2 = + * 0. + */ +public class Dual { + /** + * The real part of the dual number. + */ + public double real; + /** + * The dual part of the dual number. + */ + public double dual; + + /** + * Create a new dual with both parts zero. + */ + public Dual() { + real = 0; + dual = 0; + } + + /** + * Create a new dual number with a zero dual part. + * + * @param real + * The real part of the number. + */ + public Dual(double real) { + this.real = real; + this.dual = 0; + } + + /** + * Create a new dual number with a specified dual part. + * + * @param real + * The real part of the number. + * @param dual + * The dual part of the number. + */ + public Dual(double real, double dual) { + this.real = real; + this.dual = dual; + } + + @Override + public String toString() { + return String.format("<%f, %f>", real, dual); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + long temp; + temp = Double.doubleToLongBits(dual); + result = prime * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(real); + result = prime * result + (int) (temp ^ (temp >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Dual other = (Dual) obj; + if (Double.doubleToLongBits(dual) != Double.doubleToLongBits(other.dual)) + return false; + if (Double.doubleToLongBits(real) != Double.doubleToLongBits(other.real)) + return false; + return true; + } +} \ No newline at end of file -- cgit v1.2.3