This class represents a converter between two currencies.
17 | *
18 | *
Currency converters convert values based upon the current
19 | * exchange rate {@link Currency#getExchangeRate() exchange rate}.
20 | * If the {@link Currency#getExchangeRate() exchange rate} from the
21 | * target currency to the source currency is not set, conversion
22 | * fails. In others words, the converter from a currency A
23 | * to a currency B is independant from the converter from
24 | * B to A.
25 | *
26 | * @author Jean-Marie Dautelle
27 | * @version 5.0, January 2, 2010
28 | * @see Currency#setExchangeRate
29 | */
30 | public class CurrencyConverter extends UnitConverterImpl {
31 |
32 | /**
33 | * Holds the source currency.
34 | */
35 | private Currency _source;
36 |
37 | /**
38 | * Holds the target currency.
39 | */
40 | private Currency _target;
41 |
42 | /**
43 | * Creates the currency converter from the source currency to the target
44 | * currency.
45 | *
46 | * @param source the source currency.
47 | * @param target the target currency.
48 | * @param factor the multiplier factor from source to target.
49 | * @return the corresponding converter.
50 | */
51 | public CurrencyConverter(Currency source, Currency target) {
52 | _source = source;
53 | _target = target;
54 | }
55 |
56 | /**
57 | * Returns the source currency.
58 | *
59 | * @return the source currency.
60 | */
61 | public Currency getSource() {
62 | return _source;
63 | }
64 |
65 | /**
66 | * Returns the target currency.
67 | *
68 | * @return the target currency.
69 | */
70 | public Currency getTarget() {
71 | return _target;
72 | }
73 |
74 | @Override
75 | public CurrencyConverter inverse() {
76 | return new CurrencyConverter(_target, _source);
77 | }
78 |
79 | @Override
80 | public double convert(double x) {
81 | Number factor = _source.getExchangeRate(_target);
82 | if (factor == null)
83 | throw new UnsupportedOperationException("Exchange rate from " +
84 | _source + " to " + _target + " not set.");
85 | return factor.doubleValue() * x;
86 | }
87 |
88 | @Override
89 | public BigDecimal convert(BigDecimal value, MathContext ctx) throws ArithmeticException {
90 | Number factor = _source.getExchangeRate(_target);
91 | if (factor == null)
92 | throw new UnsupportedOperationException("Exchange rate from " +
93 | _source + " to " + _target + " not set.");
94 | if (factor instanceof BigDecimal)
95 | return value.multiply((BigDecimal) factor, ctx);
96 | if (factor instanceof org.jscience.mathematics.number.Number) {
97 | return value.multiply(((org.jscience.mathematics.number.Number)factor).decimalValue(), ctx);
98 | } else { // Reverts to double convert.
99 | return value.multiply(BigDecimal.valueOf(factor.doubleValue()), ctx);
100 | }
101 | }
102 |
103 | @Override
104 | public boolean equals(Object cvtr) {
105 | if (!(cvtr instanceof CurrencyConverter))
106 | return false;
107 | CurrencyConverter that = (CurrencyConverter) cvtr;
108 | return this._source.equals(that._source) &&
109 | this._target.equals(that._target);
110 | }
111 |
112 | @Override
113 | public int hashCode() {
114 | return _source.hashCode() + _target.hashCode();
115 | }
116 |
117 | @Override
118 | public final String toString() {
119 | return "Currency.Converter(From: " + _source + " to " + _target + ")";
120 | }
121 |
122 | @Override
123 | public boolean isLinear() {
124 | return true;
125 | }
126 |
127 | private static final long serialVersionUID = 1L;
128 |
129 | }
130 |
--------------------------------------------------------------------------------
/economics/src/main/java/org/jscience/economics/money/Money.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.economics.money;
10 |
11 | import org.unitsofmeasurement.quantity.Quantity;
12 | import org.jscience.physics.unit.BaseUnit;
13 | import org.jscience.physics.unit.Dimension;
14 |
15 | /**
16 | * This interface represents something generally accepted as a medium of
17 | * exchange, a measure of value, or a means of payment. The units for money
18 | * quantities is of type {@link Currency}.
19 | *
20 | * @author Jean-Marie Dautelle
21 | * @version 3.0, February 13, 2006
22 | */
23 | public interface Money extends Quantity {
24 |
25 | /**
26 | * Holds the base unit for money quantities (symbol "$").
27 | */
28 | public final static BaseUnit UNIT = new BaseUnit("$");
29 |
30 | /**
31 | * Holds the dimension for money quantities (dimension [$]).
32 | */
33 | public final static Dimension DIMENSION = UNIT.getDimension();
34 |
35 | }
--------------------------------------------------------------------------------
/mathematics/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 |
5 |
6 |
7 |
8 | org.jscience
9 | jscience
10 | 5.0.0-SNAPSHOT
11 |
12 | jscience-mathematics
13 | JScience Mathematics Bundle
14 | bundle
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | org.apache.felix
23 | maven-bundle-plugin
24 | 2.3.7
25 | true
26 |
27 |
28 | !org.jscience.mathematics.internal.*,org.jscience.mathematics.*
29 | org.jscience.mathematics.internal.*
30 | org.jscience.mathematics.internal.osgi.BundleActivatorImpl
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/function/Constant.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.function;
10 |
11 | import javolution.context.ObjectFactory;
12 |
13 | import org.jscience.mathematics.structure.Ring;
14 |
15 | /**
16 | *
This class represents a constant function (polynomial of degree 0).
17 | *
18 | * @author Jean-Marie Dautelle
19 | * @version 3.1, April 1, 2006
20 | */
21 | public final class Constant> extends Polynomial {
22 |
23 | /**
24 | * Default constructor.
25 | */
26 | private Constant() {
27 | }
28 |
29 | /**
30 | * Returns a constant function of specified value.
31 | *
32 | * @param value the value returned by this function.
33 | * @return the corresponding constant function.
34 | */
35 | @SuppressWarnings("unchecked")
36 | public static > Constant valueOf(R value) {
37 | Constant cst = FACTORY.object();
38 | cst._termToCoef.put(Term.ONE, value);
39 | return cst;
40 | }
41 |
42 | @SuppressWarnings("unchecked")
43 | private static final ObjectFactory FACTORY = new ObjectFactory() {
44 | protected Constant create() {
45 | return new Constant();
46 | }
47 |
48 | protected void cleanup(Constant cst) {
49 | cst._termToCoef.reset();
50 | }
51 | };
52 |
53 | /**
54 | * Returns the constant value for this function.
55 | *
56 | * @return getCoefficient(Term.CONSTANT)
57 | */
58 | public R getValue() {
59 | return getCoefficient(Term.ONE);
60 | }
61 |
62 | private static final long serialVersionUID = 1L;
63 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/function/DiscreteFunction.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.function;
10 |
11 | import java.util.List;
12 | import java.util.SortedMap;
13 |
14 | import javolution.text.Text;
15 | import javolution.util.FastList;
16 |
17 | /**
18 | *
This class represents a function defined from a mapping betweem
19 | * two sets (points and values).
20 | *
21 | *
Instance of this class can be used to approximate continuous
22 | * functions or to numerically solve differential systems.
23 | *
24 | * @author Jean-Marie Dautelle
25 | * @version 3.0, February 13, 2006
26 | */
27 | public final class DiscreteFunction extends Function {
28 |
29 | /**
30 | * Holds the point-value entries.
31 | */
32 | private SortedMap _pointValues;
33 |
34 | /**
35 | * Holds the variable.
36 | */
37 | private FastList> _variables = new FastList>();
38 |
39 | /**
40 | * Holds the interpolator.
41 | */
42 | private Interpolator _interpolator;
43 |
44 | /**
45 | * Creates the discrete function for the specified point-value entries.
46 | *
47 | * @param pointValues the point-value entries of this function.
48 | * @param interpolator the interpolator.
49 | * @param variable this function variable.
50 | */
51 | public DiscreteFunction(SortedMap pointValues,
52 | Interpolator interpolator, Variable variable) {
53 | _pointValues = pointValues;
54 | _variables.add(variable);
55 | _interpolator = interpolator;
56 | }
57 |
58 | /**
59 | * Returns the point-value entries of this discrete function.
60 | *
61 | * @return the point-value mapping.
62 | */
63 | public SortedMap getPointValues() {
64 | return _pointValues;
65 | }
66 |
67 | /**
68 | * Returns the interpolator used by this discrete function.
69 | *
70 | * @return the interpolator used to estimate the value between two points.
71 | */
72 | public Interpolator getInterpolator() {
73 | return _interpolator;
74 | }
75 |
76 | @Override
77 | public Y evaluate() {
78 | X point = _variables.get(0).get();
79 | if (point == null) {
80 | throw new FunctionException("Variable " + _variables.get(0)
81 | + " not set");
82 | }
83 | return _interpolator.interpolate(point, _pointValues);
84 | }
85 |
86 | @Override
87 | public List> getVariables() {
88 | return _variables;
89 | }
90 |
91 | private static final long serialVersionUID = 1L;
92 |
93 | @Override
94 | public Text toText() {
95 | return Text.valueOf(getClass().getName()).plus("@").plus(
96 | Text.valueOf(hashCode(), 16));
97 | }
98 |
99 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/function/FunctionException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.function;
10 |
11 | /**
12 | *
Thrown when a function operation cannot be performed.
13 | *
14 | * @author Jean-Marie Dautelle
15 | * @version 1.0, January 24, 2004
16 | */
17 | public class FunctionException extends RuntimeException {
18 |
19 | /**
20 | * Constructs a {@link FunctionException} with no detail message.
21 | */
22 | public FunctionException() {
23 | super();
24 | }
25 |
26 | /**
27 | * Constructs a {@link FunctionException} with the specified message.
28 | *
29 | * @param message the message.
30 | */
31 | public FunctionException(String message) {
32 | super(message);
33 | }
34 |
35 | private static final long serialVersionUID = 1L;
36 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/function/Interpolator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.function;
10 |
11 | import java.io.Serializable;
12 | import java.util.SortedMap;
13 |
14 | import javolution.lang.Immutable;
15 |
16 | import org.jscience.mathematics.structure.Field;
17 |
18 | /**
19 | *
This interface represents an estimator of the values at a certain point
20 | * using surrounding points and values. Interpolators are typically used
21 | * with {@link DiscreteFunction discrete functions}.
22 | *
23 | *
As a convenience {@link Interpolator.Linear linear} interpolator class
24 | * for point-values of the same {@link Field field} is provided.
25 | *
26 | *
Custom interpolators can be used between Java objects of different kind.
27 | * For example:[code]
28 | * // Creates a linear interpolator between the java.util.Date and Measures
29 | * Interpolator> linear
30 | * = new Interpolator>() { ... }
31 | * DiscreteFunction> weight
32 | * = new DiscreteFunction>(samples, linear, t);
33 | * [/code]
34 | *
35 | * @author Jean-Marie Dautelle
36 | * @version 3.0, February 13, 2006
37 | */
38 | public interface Interpolator
extends Immutable, Serializable {
39 |
40 | /**
41 | * Estimates the value at the specified point.
42 | *
43 | * @param point the point for which the value is estimated.
44 | * @param pointValues the point-value entries.
45 | * @return the estimated value at the specified point.
46 | */
47 | V interpolate(P point, SortedMap
pointValues);
48 |
49 |
50 | /**
51 | *
This class represents a linear interpolator for {@link Field field}
52 | * instances (point and values from the same field).
53 | *
54 | * @author Jean-Marie Dautelle
55 | * @version 3.0, February 13, 2006
56 | */
57 | public static class Linear> implements Interpolator {
58 |
59 | public F interpolate(F point, SortedMap pointValues) {
60 | // Searches exact.
61 | F y = pointValues.get(point);
62 | if (y != null)
63 | return y;
64 |
65 | // Searches surrounding points/values.
66 | SortedMap headMap = pointValues.headMap(point);
67 | F x1 = headMap.lastKey();
68 | F y1 = headMap.get(x1);
69 | SortedMap tailMap = pointValues.tailMap(point);
70 | F x2 = tailMap.firstKey();
71 | F y2 = tailMap.get(x2);
72 |
73 | // Interpolates.
74 | final F x = point;
75 | F deltaInv = (x2.plus(x1.opposite())).reciprocal();
76 | F k1 = (x2.plus(x.opposite())).times(deltaInv);
77 | F k2 = (x.plus(x1.opposite())).times(deltaInv);
78 | return ((y1.times(k1))).plus(y2.times(k2));
79 | }
80 |
81 | private static final long serialVersionUID = 1L;
82 | }
83 |
84 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/function/Variable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.function;
10 |
11 | import javolution.lang.Reference;
12 | import javolution.context.LocalContext;
13 |
14 | /**
15 | *
This interface represents a symbol on whose value a {@link Function}
16 | * depends. If the functions is not shared between multiple-threads the
17 | * simple {@link Variable.Local} implementation can be used.
18 | * For global functions (functions used concurrently by multiple threads)
19 | * the {@link Variable.Global} implementation with
20 | * {@link javolution.context.LocalContext context-local} settings is
21 | * recommended.
22 | *
23 | * @author Jean-Marie Dautelle
24 | * @version 3.0, February 13, 2006
25 | * @see Function#evaluate
26 | */
27 | public interface Variable extends Reference {
28 |
29 | /**
30 | * Returns the symbol for this variable.
31 | *
32 | * @return this variable's symbol.
33 | */
34 | String getSymbol();
35 |
36 | /**
37 | * This class represents a simple {@link Variable} implementation for
38 | * functions not shared between threads (non static).
39 | * Functions shared between multiple-threads should use a different
40 | * type of variable such as {@link Variable.Global}.
41 | */
42 | public static class Local implements Variable {
43 |
44 | /**
45 | * Holds the reference value.
46 | */
47 | private X _value;
48 |
49 | /**
50 | * Holds the variable symbol.
51 | */
52 | private final String _symbol;
53 |
54 | /**
55 | * Creates a new local variable with a unique symbol.
56 | *
57 | * @param symbol the variable symbol.
58 | */
59 | public Local(String symbol) {
60 | _symbol = symbol;
61 | }
62 |
63 | public String getSymbol() {
64 | return _symbol;
65 | }
66 |
67 | public X get() {
68 | return _value;
69 | }
70 |
71 | public void set(X arg0) {
72 | _value = arg0;
73 | }
74 | }
75 |
76 | /**
77 | * This class represents a simple {@link Variable} implementation with
78 | * {@link javolution.context.LocalContext context-local} values.
79 | * Instances of this class can be set independently by multiple-threads
80 | * as long as each concurrent thread executes within a
81 | * {@link javolution.context.LocalContext LocalContext}. For example:[code]
82 | * public abstract class Engine {
83 | * public static final Variable.Global> RPM
84 | * = new Variable.Global>("rpm");
85 | * public abstract Function, Amount> getTorque();
86 | * }
87 | * ...
88 | * LocalContext.enter();
89 | * try {
90 | * RPM.set(rpm);
91 | * Amount torque = myEngine.getTorque().evaluate();
92 | * } finally {
93 | * LocalContext.exit();
94 | * }[/code]
95 | * It should be noted that parameterized evaluations are performed within
96 | * a local context. Therefore, the example
97 | * above could also be rewritten:[code]
98 | * Amount torque = myEngine.getTorque().evaluate(rpm);
99 | * [/code]
100 | */
101 | public static class Global implements Variable {
102 |
103 | /**
104 | * Holds the reference value.
105 | */
106 | private LocalContext.Reference _value = new LocalContext.Reference();
107 |
108 | /**
109 | * Holds the variable symbol.
110 | */
111 | private final String _symbol;
112 |
113 | /**
114 | * Creates a new global variable with a unique symbol.
115 | *
116 | * @param symbol the variable symbol.
117 | */
118 | public Global(String symbol) {
119 | _symbol = symbol;
120 | }
121 |
122 | public String getSymbol() {
123 | return _symbol;
124 | }
125 |
126 | public X get() {
127 | return _value.get();
128 | }
129 |
130 | public void set(X arg0) {
131 | _value.set(arg0);
132 | }
133 | }
134 |
135 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/function/package.html:
--------------------------------------------------------------------------------
1 |
2 |
Provides support for fairly simple symbolic math analysis
3 | (to solve algebraic equations, integrate, differentiate, calculate
4 | expressions, and so on).
5 |
6 |
{@link org.jscience.mathematics.function.Function Functions} defined in this package
7 | can be {@link org.jscience.mathematics.function.Variable multivariate}
8 | and operate on various kind of objects such as physical measurements,
9 | vectors, matrices, all types of numbers or even the functions
10 | themselves (functions of functions)!
11 | Here is an example using {@link org.jscience.mathematics.number.Complex complex}
12 | {@link org.jscience.mathematics.function.Polynomial polynomial} functions:[code]
13 |
14 | // Defines two local variables (x, y).
15 | Variable varX = new Variable.Local("x");
16 | Variable varY = new Variable.Local("y");
17 |
18 | // f(x) = ix² + 2x + 1
19 | Polynomial x = Polynomial.valueOf(Complex.ONE, varX);
20 | Polynomial fx = x.pow(2).times(Complex.I).plus(
21 | x.times(Complex.valueOf(2, 0)).plus(Complex.ONE));
22 | System.out.println(fx);
23 | System.out.println(fx.pow(2));
24 | System.out.println(fx.differentiate(varX));
25 | System.out.println(fx.integrate(varY));
26 | System.out.println(fx.compose(fx));
27 |
28 | // Calculates expression.
29 | varX.set(Complex.valueOf(2, 3));
30 | System.out.println(fx.evaluate());
31 |
32 | > [0.0 + 1.0i]x^2 + [2.0 + 0.0i]x + [1.0 + 0.0i]
33 | > [-1.0 + 0.0i]x^4 + [0.0 + 4.0i]x^3 + [4.0 + 2.0i]x^2 + [4.0 + 0.0i]x + [1.0 + 0.0i]
34 | > [0.0 + 2.0i]x + [2.0 + 0.0i]
35 | > [0.0 + 1.0i]x^2y + [2.0 + 0.0i]xy + [1.0 + 0.0i]y
36 | > [0.0 - 1.0i]x^4 + [-4.0 + 0.0i]x^3 + [-2.0 + 6.0i]x^2 + [4.0 + 4.0i]x + [3.0 + 1.0i]
37 | > -7.0 + 1.0i
38 | [/code]
This class holds the dense vector default implementation.
28 | *
29 | * @author Jean-Marie Dautelle
30 | * @version 5.0, December 12, 2009
31 | */
32 | public class DenseVectorImpl> extends DenseVector {
33 |
34 | private static final long serialVersionUID = 0x500L;
35 | private final F[] elements;
36 |
37 | public DenseVectorImpl(F[] elements) {
38 | this.elements = elements.clone();
39 | }
40 |
41 | public DenseVectorImpl(F[] elements) {
42 | this.elements = elements.clone();
43 | }
44 |
45 | @SuppressWarnings("unchecked")
46 | public DenseVectorImpl(Vector that) {
47 | final int n = that.dimension();
48 | elements = (F[]) new Object[n];
49 | for (int i = 0; i < n; i++) {
50 | elements[i] = that.get(i);
51 | }
52 | }
53 |
54 | @Override
55 | public F get(int i) {
56 | return elements[i];
57 | }
58 |
59 | @Override
60 | public FastTable getData() {
61 | return new FastTable(elements);
62 | }
63 |
64 | @Override
65 | public int dimension() {
66 | return elements.length;
67 | }
68 |
69 | @Override
70 | public DenseVectorImpl getSubVector(List indices) {
71 | @SuppressWarnings("unchecked")
72 | F[] subVector = (F[]) new Object[indices.size()];
73 | int i = 0;
74 | for (Index index : indices) {
75 | subVector[i++] = elements[index.intValue()];
76 | }
77 | return new DenseVectorImpl(subVector);
78 | }
79 |
80 | @Override
81 | public int hashCode() {
82 | return getData().hashCode();
83 | }
84 |
85 | @Override
86 | public DenseVector minus(Vector that) {
87 | return this.plus(that.opposite());
88 | }
89 |
90 | @Override
91 | public DenseVectorImpl opposite() {
92 | final int n = elements.length;
93 | @SuppressWarnings("unchecked")
94 | F[] result = (F[]) new Object[n];
95 | for (int i = 0; i < n; i++) {
96 | result[i] = elements[i].opposite();
97 | }
98 | return new DenseVectorImpl(result);
99 | }
100 |
101 | @Override
102 | public DenseVectorImpl plus(Vector that) {
103 | final int n = that.dimension();
104 | if (n != elements.length) throw new DimensionException();
105 | @SuppressWarnings("unchecked")
106 | F[] result = (F[]) new Object[n];
107 | for (int i = 0; i < n; i++) {
108 | result[i] = elements[i].plus(that.get(i));
109 | }
110 | return new DenseVectorImpl(result);
111 | }
112 |
113 | @Override
114 | public DenseMatrixImpl tensor(Vector that) {
115 | int m = this.dimension();
116 | int n = that.dimension();
117 | @SuppressWarnings("unchecked")
118 | F[][] result = (F[][])new Object[m][n];
119 | for (int j=0; j < n; j++) {
120 | F ej = that.get(j);
121 | for (int i=0; i < m; i++) {
122 | result[i][j] = elements[i].times(ej);
123 | }
124 | }
125 | return new DenseMatrixImpl(result);
126 | }
127 |
128 | @Override
129 | public DenseVectorImpl times(F k) {
130 | final int n = elements.length;
131 | @SuppressWarnings("unchecked")
132 | F[] result = (F[]) new Object[n];
133 | for (int i = 0; i < n; i++) {
134 | result[i] = elements[i].times(k);
135 | }
136 | return new DenseVectorImpl(result);
137 | }
138 |
139 | @Override
140 | public F times(Vector that) {
141 | final int n = that.dimension();
142 | if (n != elements.length) throw new DimensionException();
143 | F sum = elements[0].times(that.get(0));
144 | for (int i = 1; i < n; i++) {
145 | sum = sum.plus(elements[i].times(that.get(i)));
146 | }
147 | return sum;
148 | }
149 |
150 | @Override
151 | public String toString() {
152 | return TextContext.getFormat(DenseVector.class).format(this);
153 | }
154 |
155 | }
156 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/internal/linear/package.html:
--------------------------------------------------------------------------------
1 |
2 |
Provides support for linear algebra
3 | in the form of {@link org.jscience.mathematics.vector.Matrix matrices} and
4 | {@link org.jscience.mathematics.vector.Vector vectors}.
5 |
6 |
With the {@link org.jscience.mathematics.vector.Matrix Matrix} class,
7 | you should be able to resolve linear systems of equations
8 | involving any kind of elements such as
9 | {@link org.jscience.mathematics.number.Rational Rational},
10 | {@link org.jscience.mathematics.number.ModuloInteger ModuloInteger} (modulo operations),
11 | {@link org.jscience.mathematics.number.Complex Complex},
12 | {@link org.jscience.mathematics.function.RationalFunction RationalFunction}, etc.
13 | The main requirement being that your element class implements the mathematical
14 | {@link org.jscience.mathematics.structure.Field Field} interface.
15 |
16 |
Most {@link org.jscience.mathematics.number numbers} and even invertible matrices
17 | themselves may implement this interface. Non-commutative multiplication is supported which
18 | allows for the resolution of systems of equations with invertible matrix coefficients (matrices of matrices).
19 |
20 |
For classes embedding automatic error calculation (e.g.
21 | {@link org.jscience.mathematics.number.Real Real} or {@link org.jscience.physics.amount.Amount Amount}),
22 | the error on the solution obtained tells you if can trust that solution or not
23 | (e.g. system close to singularity). The following example illustrates this point.
24 |
25 |
Let's say you have a simple electric circuit composed of 2 resistors in series
26 | with a battery. You want to know the voltage (U1, U2) at the nodes of the
27 | resistors and the current (I) traversing the circuit.[code]
28 | import static org.jscience.physics.units.SI.*;
29 |
30 | RealAmount R1 = RealAmount.valueOf(100, 1, OHM); // (100 ± 1) Ω
31 | RealAmount R2 = RealAmount.valueOf(300, 3, OHM); // (300 ± 3) Ω
32 | RealAmount U0 = RealAmount.valueOf(28000, 10, MILLI(VOLT)); // (28 ± 0.01) V
33 |
34 | // Equations: U0 = U1 + U2 |1 1 0 | |U1| |U0|
35 | // U1 = R1 * I => |-1 0 R1| * |U2| = |0 |
36 | // U2 = R2 * I |0 -1 R2| |I | |0 |
37 | //
38 | // A * X = B
39 | //
40 | DenseMatrix> A = DenseMatrix.valueOf(new RealAmount>[][] {
41 | { RealAmount.ONE, RealAmount.ONE, RealAmount.valueOf(0, OHM) },
42 | { RealAmount.ONE.opposite(), RealAmount.ZERO, R1 },
43 | { RealAmount.ZERO, RealAmount.ONE.opposite(), R2 } });
44 | DenseVector> B = DenseVector.valueOf(new Amount>[]
45 | { U0, RealAmount.valueOf(0, VOLT), RealAmount.valueOf(0, VOLT) });
46 | Vector> X = A.solve(B);
47 | System.out.println(X);
48 | System.out.println(X.get(2).to(MILLI(AMPERE)));
49 |
50 | > {(7.0 ± 1.6E-1) V, (21.0 ± 1.5E-1) V, (7.0E-2 ± 7.3E-4) V/Ω}
51 | > (70.0 ± 7.3E-1) mA
52 | [/code]
53 |
54 | Because the {@link org.jscience.physics.amount.RealAmount RealAmount} class guarantees
55 | the accuracy/precision of its calculations. As long as the input resistances, voltage
56 | stay within their specification range then the current is guaranteed
57 | to be (70.0 ± 7.3E-1) mA. When the inputs have no error specified,
58 | the error on the result corresponds to calculations numeric errors only
59 | (which might increase significantly if the matrix is close to singularity).
60 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/internal/matrix/DenseMatrixImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2014 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.internal.matrix;
10 |
11 | import org.jscience.mathematics.matrix.DenseMatrix;
12 | import org.jscience.mathematics.structure.Field;
13 |
14 | /**
15 | * Dense matrix default implementation.
16 | */
17 | public class DenseMatrixImpl> extends DenseMatrix {
18 |
19 | private static final long serialVersionUID = 0x500L;
20 | private final int m, n;
21 | private final F[] elements;
22 |
23 | public DenseMatrixImpl(int m, int n, F[] elements) {
24 | this.m = m;
25 | this.n = n;
26 | this.elements = elements;
27 | }
28 |
29 | @Override
30 | public final F get(int i, int j) {
31 | if ((j < 0) || (j >= n)) throw new IndexOutOfBoundsException();
32 | return elements[i * n + j];
33 | }
34 |
35 | @Override
36 | public final int numberOfRows() {
37 | return n;
38 | }
39 |
40 | @Override
41 | public final int numberOfColumns() {
42 | return m;
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/internal/matrix/DenseVectorImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2014 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.internal.matrix;
10 |
11 | import org.jscience.mathematics.matrix.DenseVector;
12 | import org.jscience.mathematics.structure.Field;
13 |
14 | /**
15 | * Dense vector default implementation.
16 | */
17 | public class DenseVectorImpl> extends DenseVector {
18 |
19 | private static final long serialVersionUID = 0x500L;
20 | private final F[] data;
21 |
22 | public DenseVectorImpl(F[] elements) {
23 | this.data = elements;
24 | }
25 |
26 | @Override
27 | public final F get(int i) {
28 | return data[i];
29 | }
30 |
31 | @Override
32 | public final int dimension() {
33 | return data.length;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/internal/matrix/SparseMatrixImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2014 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.internal.matrix;
10 |
11 | import org.jscience.mathematics.matrix.SparseMatrix;
12 | import org.jscience.mathematics.matrix.SparseVector;
13 | import org.jscience.mathematics.structure.Field;
14 |
15 | /**
16 | * Sparse matrix default implementation.
17 | */
18 | public class SparseMatrixImpl> extends SparseMatrix {
19 |
20 | private static final long serialVersionUID = 0x500L;
21 | private final SparseVector[] rows;
22 |
23 | public SparseMatrixImpl(SparseVector[] rows) {
24 | this.rows = rows;
25 | }
26 |
27 | @Override
28 | public final F get(int i, int j) {
29 | return rows[i].get(j);
30 | }
31 |
32 | @Override
33 | public final int numberOfRows() {
34 | return rows.length;
35 | }
36 |
37 | @Override
38 | public final int numberOfColumns() {
39 | return rows[0].dimension();
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/internal/matrix/SparseVectorImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2014 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.internal.matrix;
10 |
11 | import java.util.Map;
12 | import javolution.lang.MathLib;
13 | import javolution.util.Index;
14 | import org.jscience.mathematics.matrix.SparseVector;
15 | import org.jscience.mathematics.structure.Field;
16 |
17 | /**
18 | * Sparse vector default implementation (trie-based).
19 | */
20 | public class SparseVectorImpl> extends SparseVector {
21 |
22 | // Trie Implementation.
23 | private static final long serialVersionUID = 0x500L;
24 | private static final int SHIFT = 4;
25 | private static final int MASK = (1 << SHIFT) - 1;
26 | private final int dimension;
27 | private final F zero;
28 | private final Object[] nodes;
29 | private final int shift;
30 |
31 | /**
32 | * Creates a new sparse vector (empty).
33 | */
34 | public SparseVectorImpl(int dimension, F zero) {
35 | this.dimension = dimension;
36 | this.zero = zero;
37 | int shiftValue = 0;
38 | int capacity = 1 << SHIFT;
39 | while (capacity < dimension) {
40 | capacity <<= SHIFT;
41 | shiftValue += SHIFT;
42 | }
43 | this.shift = shiftValue;
44 | this.nodes = new Object[((dimension-1) >> shift) + 1];
45 | }
46 |
47 | @SuppressWarnings("unchecked")
48 | @Override
49 | public final F get(int index) {
50 | if (index >= dimension) throw new IndexOutOfBoundsException();
51 | int shiftValue = shift;
52 | Object node = nodes[index >> shiftValue];
53 | while (node != null) {
54 | if (node instanceof Entry) {
55 | Entry entry = (Entry) node;
56 | return (entry.getIndex() == index) ? entry.getValue() : zero;
57 | }
58 | shiftValue -= SHIFT;
59 | node = ((Object[])node)[(index >> shiftValue) & MASK];
60 | }
61 | return zero;
62 |
63 | }
64 |
65 | /** Adds the specified value at the specified index. */
66 | @SuppressWarnings("unchecked")
67 | public final void add(int index, F value) {
68 | Object node = nodes[index >> shift];
69 | if (node == null) {
70 | nodes[index >> shift] = new Entry(index, value);
71 | } else if (node instanceof SparseVectorImpl) { // Recurse.
72 | ((SparseVectorImpl)node).add(index & ((1 << shift) -1), value);
73 | } else {
74 | Entry entry = (Entry) node;
75 | if (entry.getIndex() == i) {
76 | entry.setValue(entry.getValue().plus(value));
77 | } else { // Collision.
78 | int newShift = shift + SHIFT;
79 | SparseVectorImpl inner = new SparseVectorImpl(dimension, zero, newShift);
80 | inner.nodes[(entry.getIndex() >> newShift) & MASK] = entry;
81 | inner.add(index, value); // Recurse.
82 | nodes[i] = inner;
83 | }
84 | }
85 | }
86 |
87 | @Override
88 | public final int dimension() {
89 | return dimension;
90 | }
91 |
92 | @Override
93 | public final F getZero() {
94 | return zero;
95 | }
96 |
97 | public void forNonZero(Consumer super F> consumer) {
98 | forNonZero(consumer, nodes);
99 | }
100 |
101 | // Attention.
102 | // Diagonale: filter(accept(Range)
103 | // row1 = x / n; x % n
104 | // row2 = x / n; x % n
105 | //
106 |
107 |
108 | @SuppressWarnings("unchecked")
109 | private static > void forNonZero(Consumer super F> consumer, Object[] nodes) {
110 | for (Object node : nodes) {
111 | if (node != null) {
112 | if (node instanceof Entry) {
113 | Entry entry = (Entry) node;
114 | consumer.accept(entry.getIndex(), entry.getValue());
115 | } else {
116 | forNonZero(consumer, (Object[])node);
117 | }
118 | }
119 | }
120 | }
121 |
122 | }
123 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/internal/number/ComplexFieldImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2014 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.internal.number;
10 |
11 | import org.jscience.mathematics.number.ComplexField;
12 | import org.jscience.mathematics.number.NumberField;
13 |
14 | /**
15 | * Default generic complex implementation.
16 | */
17 | public final class ComplexFieldImpl> extends ComplexField {
18 |
19 | private static final long serialVersionUID = 0x500L; // Version.
20 | N real, imag;
21 |
22 | public ComplexFieldImpl(N real, N imag) {
23 | this.real = real;
24 | this.imag = imag;
25 | }
26 |
27 | @Override
28 | public ComplexFieldImpl conjugate() {
29 | return new ComplexFieldImpl(real, imag.opposite());
30 | }
31 |
32 | @Override
33 | public ComplexFieldImpl divide(long n) {
34 | return new ComplexFieldImpl(real.divide(n), imag.divide(n));
35 | }
36 |
37 | @Override
38 | public N getImaginary() {
39 | return imag;
40 | }
41 |
42 | @Override
43 | public N getReal() {
44 | return real;
45 | }
46 |
47 | @Override
48 | public ComplexFieldImpl reciprocal() {
49 | N tmp = (this.real.square()).plus(this.imag.square());
50 | return new ComplexFieldImpl(this.real.divide(tmp), this.imag.divide(tmp)
51 | .opposite());
52 | }
53 |
54 | @Override
55 | public ComplexFieldImpl opposite() {
56 | return new ComplexFieldImpl(real.opposite(), imag.opposite());
57 | }
58 |
59 | @Override
60 | public ComplexFieldImpl plus(ComplexField that) {
61 | return new ComplexFieldImpl(this.real.plus(that.getReal()),
62 | this.imag.plus(that.getImaginary()));
63 | }
64 |
65 | @Override
66 | public ComplexFieldImpl times(ComplexField that) {
67 | return new ComplexFieldImpl(this.real.times(that.getReal()).minus(
68 | this.imag.times(that.getImaginary())), this.real.times(
69 | that.getImaginary()).plus(
70 | this.getImaginary().times(that.getReal())));
71 | }
72 |
73 | @Override
74 | public ComplexField times(long n) {
75 | return new ComplexFieldImpl(real.times(n), imag.times(n));
76 | }
77 |
78 | @Override
79 | public ComplexFieldImpl value() {
80 | return this;
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/internal/number/RealImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.internal.number;
10 |
11 | import javolution.lang.MathLib;
12 |
13 | import org.jscience.mathematics.number.Real;
14 |
15 | /**
16 | * Float64 default implementation.
17 | */
18 | public final class RealImpl extends Real {
19 |
20 | private static final long serialVersionUID = 0x500L; // Version.
21 | private double doubleValue;
22 |
23 | public RealImpl(double doubleValue) {
24 | this.doubleValue = doubleValue;
25 | }
26 |
27 | @Override
28 | public RealImpl divide(double value) {
29 | return new RealImpl(this.doubleValue / value);
30 | }
31 |
32 | @Override
33 | public double doubleValue() {
34 | return doubleValue;
35 | }
36 |
37 | @Override
38 | public Real exp() {
39 | return new RealImpl(MathLib.exp(doubleValue));
40 | }
41 |
42 | @Override
43 | public Real reciprocal() {
44 | return new RealImpl(1.0 / doubleValue);
45 | }
46 |
47 | @Override
48 | public Real log() {
49 | return new RealImpl(MathLib.log(doubleValue));
50 | }
51 |
52 | @Override
53 | public Real minus(double value) {
54 | return new RealImpl(this.doubleValue - value);
55 | }
56 |
57 | @Override
58 | public Real opposite() {
59 | return new RealImpl(-doubleValue);
60 | }
61 |
62 | @Override
63 | public Real plus(double value) {
64 | return new RealImpl(this.doubleValue + value);
65 | }
66 |
67 | @Override
68 | public Real pow(double e) {
69 | return new RealImpl(MathLib.pow(this.doubleValue, e));
70 | }
71 |
72 | @Override
73 | public Real sqrt() {
74 | return new RealImpl(MathLib.sqrt(doubleValue));
75 | }
76 |
77 | @Override
78 | public Real times(double value) {
79 | return new RealImpl(this.doubleValue * value);
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/internal/osgi/BundleActivatorImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.internal.osgi;
10 |
11 | import javolution.context.LogContext;
12 | import org.osgi.framework.BundleActivator;
13 | import org.osgi.framework.BundleContext;
14 | import org.osgi.framework.Constants;
15 |
16 | /**
17 | *
The OSGi activator for the jscience-mathematics bundle.
18 | *
19 | * @author Jean-Marie Dautelle
20 | * @version 5.0, October 21, 2011
21 | */
22 | public class BundleActivatorImpl implements BundleActivator {
23 |
24 | public void start(BundleContext bc) throws Exception {
25 | Object name = bc.getBundle().getHeaders().get(Constants.BUNDLE_NAME);
26 | Object version = bc.getBundle().getHeaders().get(Constants.BUNDLE_VERSION);
27 | LogContext.info("Start Bundle: ", name, ", Version: ", version);
28 |
29 | }
30 |
31 | public void stop(BundleContext bc) throws Exception {
32 | Object name = bc.getBundle().getHeaders().get(Constants.BUNDLE_NAME);
33 | Object version = bc.getBundle().getHeaders().get(Constants.BUNDLE_VERSION);
34 | LogContext.info("Stop Bundle: ", name, ", Version: ", version);
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/matrix/ComplexMatrix.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2014 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.matrix;
10 |
11 | import java.util.List;
12 |
13 | import javolution.context.ComputeContext;
14 | import javolution.util.Index;
15 |
16 | import org.jscience.mathematics.number.Complex;
17 | import org.jscience.mathematics.number.ComplexField;
18 | import org.jscience.mathematics.number.Real;
19 |
20 | /**
21 | *
A {@link DenseMatrix dense matrix} of {@link Complex complex} numbers.
A {@link DenseVector dense vector} of {@link Real} numbers.
21 | *
22 | *
Real vectors can be directly created from 64 floating-points values.
23 | * [code]
24 | * RealVector V = RealVector.of(0.1, 0.2, 0.3); // OpenCL Implementation.
25 | * double x1 = V.getValue(0);
26 | * double norm = V.normValue();
27 | * [/code]
28 | *
29 | * @author Jean-Marie Dautelle
30 | * @version 5.0, December 12, 2009
31 | * @see SparseVector
32 | */
33 | public abstract class RealVector extends DenseVector implements
34 | NormedVectorSpace, Real>, ComputeContext.Local {
35 |
36 | private static final long serialVersionUID = 0x500L; // Version.
37 |
38 | /**
39 | * Returns a real vector having the specified {@code double} values.
40 | */
41 | public static RealVector of(double... values) {
42 | return null;
43 | }
44 |
45 | /**
46 | * Returns a real vector having the specified elements.
47 | */
48 | public static RealVector of(Real... elements) {
49 | return null;
50 | }
51 |
52 | /**
53 | * Returns a real vector equivalent to the generic vector specified.
54 | */
55 | public static RealVector of(Vector that) {
56 | return (that instanceof RealVector) ? (RealVector) that : null;
57 | }
58 |
59 | /**
60 | * Returns the {@code double} value of a single element of this vector.
61 | *
62 | * @param i the element index (range [0..dimension[).
63 | * @return get(i).doubleValue().
64 | * @throws IndexOutOfBoundsException (i < 0) || (i >= getDimension())
65 | */
66 | public abstract double getValue(int i);
67 |
68 | /**
69 | * Returns the {@code double} value of the {@link NormedVectorSpace#norm()
70 | * norm} of this vector.
71 | *
72 | * @return norm().doubleValue().
73 | */
74 | public abstract double normValue();
75 |
76 | @Override
77 | public abstract RealVector cross(Vector that);
78 |
79 | @Override
80 | public abstract RealVector getSubVector(List indices);
81 |
82 | @Override
83 | public abstract RealVector minus(Vector that);
84 |
85 | @Override
86 | public abstract RealVector opposite();
87 |
88 | @Override
89 | public abstract RealVector plus(Vector that);
90 |
91 | @Override
92 | public abstract RealMatrix tensor(Vector that);
93 |
94 | @Override
95 | public abstract RealVector times(Real k);
96 |
97 | }
98 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/matrix/decomposition/LowerUpper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2014 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.matrix.decomposition;
10 |
11 | import java.util.Comparator;
12 |
13 | import javolution.context.LocalContext.Parameter;
14 |
15 | import org.jscience.mathematics.matrix.DenseMatrix;
16 | import org.jscience.mathematics.matrix.DimensionException;
17 | import org.jscience.mathematics.matrix.Matrix;
18 | import org.jscience.mathematics.matrix.SparseMatrix;
19 | import org.jscience.mathematics.number.Real;
20 | import org.jscience.mathematics.structure.Field;
21 |
22 | /**
23 | *
This interface represents the decomposition of a {@link DenseMatrix
24 | * dense matrix} A into a product of a {@link #getLower lower}
25 | * and {@link #getUpper upper} triangular matrices, L
26 | * and U respectively, such as A = P·L·U with
27 | * P a {@link #getPermutation permutation} matrix.
28 | *
29 | *
This decomposition is typically used to resolve linear systems
30 | * of equations (Gaussian elimination) or to calculate the determinant
31 | * of a square matrix (O(m³)).
32 | *
33 | *
Numerical stability is guaranteed through pivoting if the
34 | * {@link Field} elements are {@link Real real} numbers.
35 | * For others elements types, numerical stability can be ensured by setting
36 | * the {@link javolution.context.LocalContext context-local}
37 | * {@link #PIVOT_COMPARATOR pivot comparator}.
38 | *
39 | * @author Jean-Marie Dautelle
40 | * @version 5.0, January 26, 2014
41 | * @see
42 | * Wikipedia: LU decomposition
43 | */
44 | public interface LowerUpper> {
45 |
46 | /**
47 | * Holds the element comparator for pivoting. By default, pivoting is
48 | * performed for {@link Real} instances. Pivoting can be disabled
49 | * by setting the comparator to {@code null} in which case the
50 | * {@link #getPermutation permutation} matrix is the matrix identity.
51 | */
52 | public static final Parameter>
53 | PIVOT_COMPARATOR = new Parameter>() {
54 | protected Comparator> getDefault() {
55 | return null;
56 | }
57 | };
58 |
59 | /**
60 | * Returns the solution X of the equation: A * X = B with
61 | * this = A.lowerUpper() using back and forward substitutions.
62 | *
63 | * @param B the input matrix.
64 | * @return the solution X = (1 / A) * B.
65 | * @throws DimensionException if the dimensions do not match.
66 | */
67 | DenseMatrix solve(Matrix B);
68 |
69 | /**
70 | * Returns the solution X of the equation: A * X = Identity with
71 | * this = A.lowerUpper() using back and forward substitutions.
72 | *
73 | * @return this.solve(Identity)
74 | */
75 | DenseMatrix inverse();
76 |
77 | /**
78 | * Returns the determinant of the {@link Matrix} having this
79 | * decomposition.
80 | */
81 | F determinant();
82 |
83 | /**
84 | * Returns the lower matrix decomposition (L) with diagonal
85 | * elements equal to the multiplicative identity (one) for F.
86 | */
87 | DenseMatrix getLower();
88 |
89 | /**
90 | * Returns the upper matrix decomposition (U).
91 | */
92 | DenseMatrix getUpper();
93 |
94 | /**
95 | * Returns the permutation matrix (P).
96 | */
97 | SparseMatrix getPermutation();
98 |
99 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/matrix/decomposition/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 |
Provides support for linear algebra
3 | in the form of {@link org.jscience.mathematics.matrix.Vector vectors}
4 | and {@link org.jscience.mathematics.matrix.Matrix matrices}.
5 | .
6 |
7 |
With the {@link org.jscience.mathematics.matrix.Matrix Matrix} class,
8 | you should be able to resolve linear systems of equations
9 | involving any kind of elements such as
10 | {@link org.jscience.mathematics.number.Rational Rational},
11 | {@link org.jscience.mathematics.number.ModuloInteger ModuloInteger} (modulo operations),
12 | {@link org.jscience.mathematics.number.ComplexField Complex},
13 | {@link org.jscience.mathematics.function.RationalFunction RationalFunction}, etc.
14 | The main requirement being that your element class implements the mathematical
15 | {@link org.jscience.mathematics.structure.Field Field} interface.
16 |
17 |
Most {@link org.jscience.mathematics.number numbers} and even invertible matrices
18 | themselves may implement this interface. Non-commutative multiplication is supported which
19 | allows for the resolution of systems of equations with invertible matrix coefficients (matrices of matrices).
20 |
21 |
For classes embedding automatic error calculation (e.g.
22 | {@link org.jscience.mathematics.number.Real Real}
23 | the error on the solution obtained tells you if can trust that solution or not
24 | (e.g. system close to singularity). The following example illustrates this point.
25 |
26 |
Let's say you have a simple electric circuit composed of 2 resistors in series
27 | with a battery. You want to know the voltage (U1, U2) at the nodes of the
28 | resistors and the current (I) traversing the circuit.
29 | [code]
30 | Amount R1 = Amount.of(Real.of("100 ± 1"), OHM); // (100 ± 1) Ω
31 | Amount R2 = Amount.of(Real.of("300 ± 3"), OHM); // (300 ± 3) Ω
32 | Amount U0 = Amount.of(Real.of("28 ± 0.01"), VOLT); // (28 ± 0.01) V
33 |
34 | // Equations: U0 = U1 + U2 |1 1 0 | |U1| |U0|
35 | // U1 = R1 * I => |-1 0 R1| * |U2| = |0 |
36 | // U2 = R2 * I |0 -1 R2| |I | |0 |
37 | //
38 | // A * X = B
39 | //
40 | Matrix> A = Matrices.denseMatrix(
41 | Vectors.denseVector(Amount.ONE, Amount.ONE, Amount.of(Real.ZERO, OHM)),
42 | Vectors.denseVector(Amount.ONE.opposite(), Amount.ZERO, R1),
43 | Vectors.denseVector(Amount.ZERO, Amount.ONE.opposite(), R2));
44 | AmountVector> B = AmountVector.of(
45 | U0, Amount.of(Real.ZERO, VOLT), Amount.of(Real.ZERO, VOLT));
46 | Vector> X = A.solve(B);
47 | System.out.println(X);
48 | System.out.println(X.get(2).to(MILLI(AMPERE)));
49 |
50 | > {(7.0 ± 1.6E-1) V, (21.0 ± 1.5E-1) V, (7.0E-2 ± 7.3E-4) V/Ω}
51 | > (70.0 ± 7.3E-1) mA
52 | [/code]
53 |
54 | Because the {@link org.jscience.mathematics.number.Real Real} class guarantees
55 | the accuracy/precision of its calculations. As long as the input resistances, voltage
56 | stay within their specification range then the current is guaranteed
57 | to be (70.0 ± 7.3E-1) mA. When the inputs have no error specified,
58 | the error on the result corresponds to calculations numeric errors only
59 | (which might increase significantly if the matrix is close to singularity).
60 |
61 |
A few vectors/matrices such as {@link RealVector}/{@link RealMatrix} or
62 | {@link ComplexVector}/{@link ComplexMatrix} are accelerated through Javolution
63 | {@link javolution.context.ComputeContext ComputeContext} and there operations
64 | can be efficiently chained for best performance on GPUs devices and multi-cores CPUs.
65 | [code]
66 | FloatMatrix A, B;
67 | FloatMatrix C;
68 | ComputeContext ctx = ComputeContext.enter();
69 | try {
70 | // Equivalent to the Matlab code: C = inv((A' * B) * 12.0)
71 | C = A.transpose().times(B).times(12).invert();
72 | C.export(); // Moves to global memory.
73 | } finally {
74 | ctx.exit(); // Releases local device memory buffers.
75 | }[/code]
Provides common types of numbers most of them implementing the
3 | {@link org.jscience.mathematics.structure.Field field} interface.
4 |
5 |
Although numbers defined in this package are not as fast as primitives types
6 | (e.g. int or double). They have many
7 | advantages (such as arbitrary size for {@link org.jscience.mathematics.number.LargeInteger LargeInteger}
8 | or precision for {@link org.jscience.mathematics.number.Real Real}) which
9 | make them irreplaceable in some calculations. This can be illustrated with the following example:
16 | The mathematically correct value is z=1. However, Java compilers
17 | using ANSI/IEEE double precision numbers evaluate z=2. Not even the first
18 | digit is correct! This is due to a rounding error occurring when subtracting
19 | two nearly equal floating point numbers. Now, lets write the same formula
20 | using {@link org.jscience.mathematics.number.Real Real} numbers:
21 | int accuracy = 20; // 20 decimal zeros for integer values.
22 | Real x = Real.of(10864, accuracy);
23 | Real y = Real.of(18817, accuracy);
24 | Real z = x.pow(4).times(9).plus(y.pow(4).opposite()).plus(y.pow(2).times(2));
25 | System.out.println("Result : " + z);
26 |
27 | > Result : 1.00000
28 |
29 | Not only the correct result is returned, but this result is also guaranteed to be 1 ± 0.00001.
30 | Only exact digits are written out, for example the following displays the first exact
31 | digits of sqrt(2):
39 |
40 | */
41 | package org.jscience.mathematics.number;
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/structure/Field.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.structure;
10 |
11 | /**
12 | * An algebraic structure in which the operations of
13 | * addition, subtraction, multiplication and division (except division by zero)
14 | * may be performed. It is not required for the multiplication to be
15 | * commutative (non commutative fields are also called division rings
16 | * or skew fields).
17 | *
18 | * @param The structure type.
19 | * @author Jean-Marie Dautelle
20 | * @version 3.0, February 13, 2006
21 | * @see
22 | * Wikipedia: Field (mathematics)
23 | */
24 | public interface Field extends Ring, GroupMultiplicative {
25 |
26 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/structure/GroupAdditive.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.structure;
10 |
11 | /**
12 | * A structure with a binary additive operation (+), satisfying the group
13 | * axioms (associativity, neutral element, inverse element and closure).
14 | *
15 | * @param The structure type.
16 | * @author Jean-Marie Dautelle
17 | * @version 3.0, February 13, 2006
18 | * @see
19 | * Wikipedia: Mathematical Group
20 | */
21 | public interface GroupAdditive extends Structure {
22 |
23 | /**
24 | * Returns the sum of this object with the one specified.
25 | *
26 | * @param that the object to be added.
27 | * @return this + that.
28 | */
29 | G plus(G that);
30 |
31 | /**
32 | * Returns the additive inverse of this object. It is the object such as
33 | * this.plus(this.opposite()) == ZERO,
34 | * with ZERO being the additive identity.
35 | *
36 | * @return -this.
37 | */
38 | G opposite();
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/structure/GroupMultiplicative.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.structure;
10 |
11 | /**
12 | * A structure with a binary multiplicative operation (·), satisfying the
13 | * group axioms (associativity, neutral element, inverse element and closure).
14 | *
15 | * @param The structure type.
16 | * @author Jean-Marie Dautelle
17 | * @version 3.0, February 13, 2006
18 | * @see
19 | * Wikipedia: Mathematical Group
20 | */
21 | public interface GroupMultiplicative extends Structure {
22 |
23 | /**
24 | * Returns the product of this object with the one specified.
25 | *
26 | * @param that the object multiplier.
27 | * @return this · that.
28 | */
29 | G times(G that);
30 |
31 | /**
32 | * Returns the multiplicative inverse of this object. It it the object
33 | * such as {@code this.times(this.reciprocal()) == ONE},
34 | * with ONE being the multiplicative identity.
35 | *
36 | *
Note: For coherence, implementations should provide a multiplicative
37 | * inverse for ZERO (e.g. INFINITY) for which
38 | * {@code ZERO.times(ZERO.reciprocal()) == ONE}.
39 | *
40 | * @return ONE / this.
41 | */
42 | G reciprocal();
43 |
44 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/structure/NormedVectorSpace.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.structure;
10 |
11 | /**
12 | * A vector space on which a positive vector length or size is defined.
13 | *
14 | * @param The structure type of the vector.
15 | * @param The structure type of the scalar.
16 | * @author Jean-Marie Dautelle
17 | * @version 3.0, February 13, 2006
18 | * @see
19 | * Wikipedia: Normed Vector Space
20 | */
21 | public interface NormedVectorSpace> extends VectorSpace {
22 |
23 | /**
24 | * Returns the positive length or size of this vector (Euclidean Norm).
25 | *
26 | * @return |this|.
27 | * @see
28 | * Wikipedia: Vector Norm
29 | */
30 | F norm();
31 |
32 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/structure/OrderedField.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.structure;
10 |
11 | /**
12 | * A field together with a total ordering of its elements that is compatible
13 | * with the field operations.
14 | *
15 | * @param The structure type.
16 | * @author Jean-Marie Dautelle
17 | * @version 3.0, February 13, 2006
18 | * @see
19 | * Wikipedia: Ordered Field
20 | */
21 | public interface OrderedField extends Field, Comparable {
22 |
23 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/structure/Ring.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.structure;
10 |
11 | /**
12 | * An algebraic structure with two binary operations addition and
13 | * multiplication (+ and ·), such that (R, +) is an abelian group,
14 | * (R, ·) is a monoid and the multiplication distributes over the addition.
15 | *
16 | * @param The structure type.
17 | * @author Jean-Marie Dautelle
18 | * @version 3.0, February 13, 2006
19 | * @see
20 | * Wikipedia: Mathematical Ring
21 | */
22 | public interface Ring extends GroupAdditive {
23 |
24 | /**
25 | * Returns the product of this object with the one specified.
26 | *
27 | * @param that the object multiplier.
28 | * @return this · that.
29 | */
30 | R times(R that);
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/structure/Structure.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.structure;
10 |
11 | /**
12 | * A mathematical structure on a set or more generally a type.
13 | *
14 | * @param The structure type.
15 | * @author Jean-Marie Dautelle
16 | * @version 3.0, February 13, 2006
17 | * @see
18 | * Wikipedia: Mathematical Structure
19 | */
20 | public interface Structure {
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/structure/VectorSpace.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.structure;
10 |
11 | /**
12 | * A vector space over a field with two operations, vector addition and
13 | * scalar multiplication.
14 | *
15 | * @param The structure type of the vector.
16 | * @param The structure type of the scalar.
17 | * @author Jean-Marie Dautelle
18 | * @version 3.0, February 13, 2006
19 | * @see
20 | * Wikipedia: Vector Space
21 | */
22 | public interface VectorSpace> extends GroupAdditive {
23 |
24 | /**
25 | * Returns the scalar multiplication of this vector by the specified
26 | * field element.
27 | *
28 | * @param a the field element,
29 | * @return this · a.
30 | */
31 | V times(F a);
32 |
33 | }
--------------------------------------------------------------------------------
/mathematics/src/main/java/org/jscience/mathematics/structure/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 |
Provides mathematical sets (identified by the class parameter) associated to binary operations,
3 | such as multiplication or addition, satisfying certain axioms.
4 |
5 |
For example,
6 | {@link org.jscience.mathematics.number.Real Real} is a
7 | {@link org.jscience.mathematics.structure.OrderedField OrderedField<Real>},
8 | but
9 | {@link org.jscience.mathematics.number.LargeInteger LargeInteger} is only a
10 | {@link org.jscience.mathematics.structure.Ring Ring<LargeInteger>} as its
11 | elements do not have multiplicative inverse (except for one).
12 |
13 |
To implement a structure means not only that some operations are now available
14 | but also that some properties (such as associativity and distributivity) must be verified.
15 | For example, the declaration: [code]class Quaternions implements Field[/code]
16 | Indicates that addition (+), multiplication (·) and their respective inverses
17 | are automatically defined for Quaternions objects; but also that (·) is distributive over (+),
18 | both operations (+) and (·) are associative and (+) is commutative.
19 | */
20 | package org.jscience.mathematics.structure;
21 |
22 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/TestJavolutionBugs.java:
--------------------------------------------------------------------------------
1 | package org.jscience;
2 |
3 | import javolution.text.TextBuilder;
4 | import junit.framework.TestCase;
5 |
6 | /**
7 | * Checks for some javolution bugs that can break JScience stuff. These have obviously to be fixed in javolution before
8 | * things are right. :-)
9 | * @author hps
10 | * @since 06.02.2010
11 | */
12 | public class TestJavolutionBugs extends TestCase {
13 |
14 | public void testTextformat() {
15 | final long c = 10000000000L;
16 | final TextBuilder builder = javolution.text.TextBuilder.newInstance();
17 | assertEquals("" + c, builder.append(c).toString());
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/mathematics/number/AbstractFloatTestSuite.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2007 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.number;
10 |
11 | import static javolution.context.LogContext.info;
12 |
13 | import java.util.List;
14 |
15 | import javolution.lang.MathLib;
16 |
17 | import org.jscience.mathematics.number.Number;
18 | import org.jscience.mathematics.number.util.NumberHelper;
19 | import org.jscience.util.Pair;
20 |
21 | /**
22 | * Additional tests for all floating point {@link Number} classes that are not covered in
23 | * {@link AbstractNumberTestSuite}.
24 | * @since 22.12.2008
25 | * @author Hans-Peter Störr
26 | * @param the type of number to test
27 | */
28 | public abstract class AbstractFloatTestSuite> extends AbstractNumberTestSuite {
29 |
30 | AbstractFloatTestSuite(NumberHelper helper) {
31 | super(helper);
32 | }
33 |
34 | /**
35 | * Generates some floating point testvalues suitable in range for all floating point classes.
36 | */
37 | @Override
38 | protected void initTestValues(List> values) {
39 | values.add(Pair.make(0.0, _helper.getZero()));
40 | values.add(Pair.make(1.0, _helper.getOne()));
41 | values.add(Pair.make(0.0, _helper.valueOf(1234.9384).minus(_helper.valueOf(1234.9384))));
42 | for (double d : new double[] { 0.0, 1.0, 0.01, -0.02, 0.1, 0.9, -0.1, -0.9, 1.1, 10, 100, 1234.5678,
43 | -1234.5678, -9876.5432, 1000000000.0, 2.0003 , 394239234954323349.0 }) {
44 | values.add(Pair.make(d, _helper.valueOf(d)));
45 | }
46 | }
47 |
48 | public void testInverse() {
49 | info(" inverse");
50 | for (final Pair p : getTestValues()) {
51 | if (0 != p._x) {
52 | doTest(new AbstractNumberTest("Testing inverse " + p, 1.0 / p._x, _helper) {
53 | @Override
54 | T operation() throws Exception {
55 | return _helper.invokeMethod("inverse", p._y);
56 | }
57 | });
58 | }
59 | }
60 | }
61 |
62 | public void testSqrt() {
63 | info(" sqrt");
64 | for (final Pair p : getTestValues()) {
65 | if (0 <= p._x) {
66 | doTest(new AbstractNumberTest("Testing sqrt " + p, MathLib.sqrt(p._x), _helper) {
67 | @Override
68 | T operation() throws Exception {
69 | return _helper.invokeMethod("sqrt", p._y);
70 | }
71 | });
72 | }
73 | }
74 | }
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/mathematics/number/AbstractIntegerTestSuite.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2007 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.number;
10 |
11 | import static javolution.context.LogContext.info;
12 |
13 |
14 | import java.util.List;
15 |
16 | import javolution.lang.MathLib;
17 |
18 | import org.jscience.mathematics.number.Number;
19 | import org.jscience.mathematics.number.util.NumberHelper;
20 | import org.jscience.util.Pair;
21 |
22 | /**
23 | * Common tests for all integer {@link Number} classes.
24 | * @author hps
25 | * @since 22.12.2008
26 | * @param
27 | */
28 | public abstract class AbstractIntegerTestSuite> extends AbstractNumberTestSuite {
29 |
30 | /** Sets the {@link NumberHelper} to use. */
31 | AbstractIntegerTestSuite(NumberHelper helper) {
32 | super(helper);
33 | }
34 |
35 | /**
36 | * Generates some integer point testvalues suitable in range for all integer classes.
37 | */
38 | @Override
39 | protected void initTestValues(List> values) {
40 | values.add(Pair.make(0.0, _helper.getZero()));
41 | values.add(Pair.make(1.0, _helper.getOne()));
42 | values.add(Pair.make(0.0, _helper.valueOf(12345).minus(_helper.valueOf(12345))));
43 | for (double d : new double[] { 0, 1, -1, 8, 33, 12345678, -12345678, 87654321 }) {
44 | values.add(Pair.make(d, _helper.valueOf(d)));
45 | }
46 | /* for (double d = 2; d < 100; d++) {
47 | values.add(Pair.make(d, _helper.valueOf(d)));
48 | values.add(Pair.make(-d, _helper.valueOf(-d)));
49 | } */
50 | }
51 |
52 | /**
53 | * This is different for integers than for Floating points.
54 | */
55 | @Override
56 | public void testDivide() {
57 | info(" divide");
58 | for (final Pair p : getTestValues()) {
59 | for (final Pair q : getTestValues()) {
60 | if (0 != q._x) {
61 | double expected = p._x / q._x;
62 | expected = 0 > expected ? -MathLib.floor(-expected) : MathLib.floor(expected);
63 | // insufficient precision of double :
64 | if (Long.MAX_VALUE == p._x && Long.MIN_VALUE == q._x) expected = 0;
65 | doTest(new AbstractNumberTest("Testing divide " + p._x + "," + q._x, expected, _helper) {
66 | @SuppressWarnings("unchecked")
67 | @Override
68 | T operation() throws Exception {
69 | Class cl = (Class) p._y.getClass();
70 | return (T) cl.getMethod("divide", cl).invoke(p._y, q._y);
71 | }
72 | });
73 | }
74 | }
75 | }
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/mathematics/number/AbstractNumberTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2007 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.number;
10 |
11 | import static javolution.testing.TestContext.assertEquals;
12 | import static javolution.testing.TestContext.assertTrue;
13 |
14 | import java.lang.reflect.InvocationTargetException;
15 |
16 | import javolution.lang.MathLib;
17 | import javolution.testing.TestCase;
18 | import javolution.testing.TestContext;
19 |
20 | import org.jscience.mathematics.number.util.NumberHelper;
21 |
22 | /**
23 | * A testcase that executes an operation and compares the {@link Number#doubleValue()} of the result with a given
24 | * expected result. If the expected result is 0 we check that the result should be less than {@link #EPSILON}, otherwise
25 | * the quotient should differ by at most {@link #EPSILON} from 1.
26 | * @since 22.12.2008
27 | * @author Hans-Peter Störr
28 | * @param the type of number to test
29 | */
30 | public abstract class AbstractNumberTest> extends TestCase {
31 |
32 | /** The maximum allowable relative difference of the result from the expected result. */
33 | protected double EPSILON = 1e-9;
34 |
35 | final double _expected;
36 | final NumberHelper _helper;
37 | final String _description;
38 | T _value;
39 | Exception _exception;
40 |
41 | /**
42 | * Sets the expected values.
43 | * @param description a description that can be printed in failures etc.
44 | * @param helper helper to be used in the test
45 | */
46 | public AbstractNumberTest(final String description, final double expected, final NumberHelper helper) {
47 | _expected = expected;
48 | _helper = helper;
49 | _description = description;
50 | }
51 |
52 | /**
53 | * Calls {@link #operation()} and catches Exceptions for later validation.
54 | * @see javolution.testing.TestCase#execute()
55 | */
56 | @Override
57 | public final void execute() {
58 | try {
59 | _value = operation();
60 | } catch (final InvocationTargetException e) {
61 | _exception = (Exception) e.getTargetException();
62 | } catch (final Exception e) {
63 | _exception = e;
64 | }
65 | }
66 |
67 | /**
68 | * Checks that there was no exception and that the result is approximately equal to the expected result.
69 | * @see javolution.testing.TestCase#validate()
70 | */
71 | @Override
72 | public final void validate() {
73 | if (null != _exception) _exception.printStackTrace();
74 | assertEquals(null, _exception, getName().toString());
75 | assertTrue(null != _value, getName() + ": no value received");
76 | compareresult();
77 | }
78 |
79 | /**
80 | * Compares {@link #_value} and {@link #_expected} after normalizing them with {@link #_suite}'s
81 | * {@link AbstractNumberTestSuite#normalize(Number)} or {@link AbstractNumberTestSuite#normalizeExpected(double)}.
82 | * The result of the comparison is {@link TestContext#assertTrue(boolean, String)}ed.
83 | */
84 | void compareresult() {
85 | assertTrue(equal(_value.doubleValue(), _expected), getName().toString() + " but got " + _value.doubleValue());
86 |
87 | }
88 |
89 | /** Verifies whether two numbers are approximately equal. */
90 | private boolean equal(final double result, final double expected) {
91 | boolean equal;
92 | if (0 == _expected) equal = EPSILON > MathLib.abs(result);
93 | else equal = EPSILON > MathLib.abs(result / expected - 1);
94 | return equal;
95 | }
96 |
97 | @Override
98 | public String getName() {
99 | return _description + " expecting " + _expected;
100 | }
101 |
102 | /**
103 | * We free the calculated resources to avoid memory problems.
104 | * @see javolution.testing.TestCase#tearDown()
105 | */
106 | @Override
107 | public void tearDown() {
108 | _value = null;
109 | _exception = null;
110 | super.tearDown();
111 | }
112 |
113 | /** Should return the value of the operation to test and set _expected to the expected value. */
114 | abstract T operation() throws Exception;
115 | }
116 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/mathematics/number/DecimalTestSuite.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2007 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.number;
10 |
11 | import static javolution.context.LogContext.info;
12 | import static javolution.testing.TestContext.assertEquals;
13 | import static javolution.testing.TestContext.assertTrue;
14 |
15 |
16 | import java.util.List;
17 |
18 | import org.jscience.mathematics.number.util.NumberHelper;
19 | import org.jscience.util.Pair;
20 |
21 | import javolution.context.LocalContext;
22 | import javolution.lang.MathLib;
23 | import javolution.testing.TestCase;
24 | import javolution.testing.TestContext;
25 |
26 | /**
27 | * Instantiation of the generic tests of the {@link AbstractFloatTestSuite} for {@link Decimal} and some further
28 | * tests that are specific to {@link Decimal}.
29 | * We omit getExponent, getSignificand, times(long) since these are trivial.
30 | * @since 23.12.2008
31 | * @author Hans-Peter Störr
32 | */
33 | public class DecimalTestSuite extends AbstractFloatTestSuite {
34 |
35 | /** Sets the needed helper class. */
36 | public DecimalTestSuite() {
37 | super(NumberHelper.DECIMAL);
38 | }
39 |
40 | /**
41 | * We add a couple of values with different precision.
42 | * @see org.jscience.mathematics.number.AbstractFloatTestSuite#initTestValues(java.util.List)
43 | */
44 | @Override
45 | protected void initTestValues(List> values) {
46 | super.initTestValues(values);
47 | values.add(Pair.make(0.7234938, Decimal.valueOf("0.7234938")));
48 | values.add(Pair.make(0.7234938, Decimal.valueOf("0.72349380000000000000000000000000000000")));
49 | }
50 |
51 | public void testConstants() {
52 | info(" constants");
53 | doTest(new SimpleTestCase() {
54 | @Override
55 | public void execute() {
56 | assertEquals(Decimal.valueOf(1), Decimal.ONE);
57 | assertEquals(Decimal.valueOf(0), Decimal.ZERO);
58 | assertTrue(Decimal.NaN.isNaN());
59 | }
60 | });
61 | }
62 |
63 | public void testRound() {
64 | info(" round");
65 | for (final Pair p : getTestValues()) {
66 | doTest(new AbstractNumberTest("Testing round " + p, MathLib.round(p._x), _helper) {
67 | @Override
68 | Decimal operation() throws Exception {
69 | final LargeInteger rounded = p._y.round();
70 | return Decimal.valueOf(rounded, 0);
71 | }
72 | });
73 | }
74 | }
75 |
76 | public void testSetDigits() {
77 | info(" setDigits");
78 | for (final Pair p : getTestValues()) {
79 | doTest(new SimpleTestCase() {
80 | @Override
81 | public void execute() {
82 | Decimal v1 = _helper.valueOf(0.123);
83 | try {
84 | LocalContext.enter();
85 | Decimal.setDigits(50);
86 | Decimal v2 = v1.reciprocal();
87 | final int dl = v2.getSignificand().digitLength();
88 | TestContext.assertTrue(50 == dl, "" + dl);
89 | } finally {
90 | LocalContext.exit();
91 | }
92 | // now we should have a different digitlength
93 | Decimal v2 = v1.reciprocal();
94 | final int dl = v2.getSignificand().digitLength();
95 | TestContext.assertTrue(50 != dl, "" + dl);
96 | }
97 | });
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/mathematics/number/SimpleTestCase.java:
--------------------------------------------------------------------------------
1 | package org.jscience.mathematics.number;
2 |
3 | import javolution.testing.TestCase;
4 |
5 | /**
6 | * A very simple testcase where there is no point of separating the validation from the execution - the validation is
7 | * done right in the {@link #execute()} method. Probably a deviation from the {@link TestCase} philosophy, but I don't
8 | * know any better.
9 | * @author hps
10 | * @since 25.01.2010
11 | */
12 | public abstract class SimpleTestCase extends TestCase {
13 |
14 | @Override
15 | public void validate() throws Exception {
16 | // empty
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/mathematics/number/TestFloat64.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2007 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.number;
10 |
11 | import org.jscience.mathematics.number.Real;
12 | import org.jscience.mathematics.number.util.NumberHelper;
13 |
14 | /**
15 | * Instantiation of the generic tests of the {@link AbstractFloatTestSuite} for {@link Real} and some further tests
16 | * that are specific to {@link Real}.
17 | * @since 23.12.2008
18 | * @author Hans-Peter Störr
19 | */
20 | public class TestFloat64 extends AbstractFloatTestSuite {
21 |
22 | /** Sets the needed helper class. */
23 | public TestFloat64() {
24 | super(NumberHelper.FLOAT64);
25 | }
26 |
27 | /**
28 | * Overridden to do nothing since it has no isZero().
29 | */
30 | @Override
31 | public void testIsPositive() {
32 | // not there 8-{
33 | }
34 |
35 | /**
36 | * Overridden to do nothing since it has no isZero().
37 | */
38 | @Override
39 | public void testIsNegative() {
40 | // not there 8-{
41 | }
42 |
43 | /**
44 | * Overridden to do nothing since it has no isZero().
45 | */
46 | @Override
47 | public void testIsZero() {
48 | // not there 8-{
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/mathematics/number/TestInteger64.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2007 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.mathematics.number;
10 |
11 | import javolution.lang.MathLib;
12 |
13 | import org.jscience.mathematics.number.Integer64;
14 | import org.jscience.mathematics.number.util.NumberHelper;
15 |
16 | /**
17 | * Instantiation of the generic tests of the {@link AbstractFloatTestSuite} for {@link Integer64} and some further tests
18 | * that are specific to {@link Integer64}.
19 | * @since 23.12.2008
20 | * @author Hans-Peter Störr
21 | */
22 | public class TestInteger64 extends AbstractIntegerTestSuite {
23 |
24 | /** Sets the needed helper class. */
25 | public TestInteger64() {
26 | super(NumberHelper.INTEGER64);
27 | }
28 |
29 | @Override
30 | protected double getMaxNumber() {
31 | return MathLib.pow(2, 63);
32 | }
33 |
34 | /**
35 | * Overridden to do nothing since it has no isZero().
36 | */
37 | @Override
38 | public void testIsPositive() {
39 | // not there 8-{
40 | }
41 |
42 | /**
43 | * Overridden to do nothing since it has no isZero().
44 | */
45 | @Override
46 | public void testIsNegative() {
47 | // not there 8-{
48 | }
49 |
50 | /**
51 | * Overridden to do nothing since it has no isZero().
52 | */
53 | @Override
54 | public void testIsZero() {
55 | // not there 8-{
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/mathematics/number/TestRational.java:
--------------------------------------------------------------------------------
1 | package org.jscience.mathematics.number;
2 |
3 | import static javolution.context.LogContext.info;
4 |
5 | import static javolution.testing.TestContext.assertEquals;
6 |
7 | import java.util.List;
8 |
9 | import org.jscience.mathematics.number.util.NumberHelper;
10 | import org.jscience.util.Pair;
11 |
12 | import javolution.lang.MathLib;
13 | import javolution.testing.TestCase;
14 | import javolution.testing.TestContext;
15 |
16 | public class TestRational extends AbstractNumberTestSuite {
17 |
18 | public TestRational() {
19 | super(NumberHelper.RATIONAL);
20 | }
21 |
22 | @Override
23 | protected void initTestValues(List> values) {
24 | values.add(Pair.make(0.0, _helper.getZero()));
25 | values.add(Pair.make(1.0, _helper.getOne()));
26 | for (double d : new double[] { 0.0, 1.0, 43234, -9382 }) {
27 | values.add(Pair.make(d, _helper.valueOf(MathLib.round(d))));
28 | }
29 | for (long numerator : new long[] { 0, 1, 3, 7, 67, 35 * 67 }) {
30 | for (long denominator : new long[] { 1, 3, 67, 23 * 67 }) {
31 | values.add(Pair.make(numerator * 1.0 / denominator, Rational.valueOf(numerator, denominator)));
32 | values.add(Pair.make(-numerator * 1.0 / denominator, Rational.valueOf(-numerator, denominator)));
33 | }
34 | }
35 | }
36 |
37 | public void testRound() {
38 | info(" round");
39 | for (final Pair p : getTestValues()) {
40 | doTest(new AbstractNumberTest("Testing round " + p, MathLib.round(p._x), _helper) {
41 | @Override
42 | Rational operation() throws Exception {
43 | return Rational.valueOf(p._y.round(), LargeInteger.ONE);
44 | }
45 | });
46 | }
47 | }
48 |
49 | public void testTimesLong() {
50 | info(" timeslong");
51 | for (final Pair p : getTestValues()) {
52 | for (final Pair q : getTestValues()) {
53 | final long ql = q._y.getDividend().longValue();
54 | doTest(new AbstractNumberTest("Testing round " + p + ", " + ql, p._x * ql, _helper) {
55 | @Override
56 | Rational operation() throws Exception {
57 | return p._y.times(ql);
58 | }
59 | });
60 | }
61 | }
62 | }
63 |
64 | public void testValueOfNoDiv() {
65 | info(" valueOfNoDiv");
66 | for (final Pair p : getTestValues()) {
67 | final long v = p._y.getDividend().longValue();
68 | doTest(new AbstractNumberTest("Testing[ valueOfNoDiv " + v, v, _helper) {
69 | @Override
70 | Rational operation() throws Exception {
71 | return Rational.valueOf(v + "");
72 | }
73 | });
74 | }
75 | }
76 |
77 | public void testNormalization() {
78 | info(" normalization");
79 | doTest(new SimpleTestCase() {
80 | @Override
81 | public void execute() {
82 | Rational norm = Rational.valueOf(123 * 43423, 839 * 43423);
83 | TestContext.assertEquals(123L, norm.getDividend().longValue(), (" normalize " + norm));
84 | TestContext.assertEquals(839L, norm.getDivisor().longValue(), (" normalize " + norm));
85 | }
86 | });
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/mathematics/number/util/DoubleInterval.java:
--------------------------------------------------------------------------------
1 | package org.jscience.mathematics.number.util;
2 |
3 | import static java.lang.StrictMath.nextAfter;
4 | import static java.lang.StrictMath.nextUp;
5 |
6 | import java.math.BigDecimal;
7 |
8 | import org.jscience.mathematics.number.Number;
9 |
10 | /**
11 | * A feeble attempt at double interval arithmetics.
12 | * @author hps
13 | * @since 20.02.2009
14 | */
15 | public class DoubleInterval extends Number {
16 |
17 | public static final DoubleInterval ZERO = new DoubleInterval(0, 0);
18 | public static final DoubleInterval ONE = new DoubleInterval(1, 1);
19 | public static final DoubleInterval NaN = new DoubleInterval(Double.NaN, Double.NaN);
20 |
21 | /** SUID */
22 | private static final long serialVersionUID = -1798040855774523462L;
23 |
24 | private final double _lower;
25 | private final double _upper;
26 |
27 | public DoubleInterval(final double lower, final double upper) {
28 | if (Double.isNaN(upper) || Double.isNaN(lower)) {
29 | _lower = Double.NaN;
30 | _upper = Double.NaN;
31 | } else {
32 | assert lower <= upper : lower + ">" + upper;
33 | _lower = lower;
34 | _upper = upper;
35 | }
36 | }
37 |
38 | public static DoubleInterval valueOf(final double lower, final double upper) {
39 | return new DoubleInterval(lower, upper);
40 | }
41 |
42 | /** Rounds one ulp outward for operations that are within at most 1 ulp of the exact value. */
43 | private static DoubleInterval outward(final double lower, final double upper) {
44 | return new DoubleInterval(nextAfter(lower, Double.NEGATIVE_INFINITY), nextUp(upper));
45 | }
46 |
47 | public double lower() {
48 | return _lower;
49 | }
50 |
51 | public double upper() {
52 | return _upper;
53 | }
54 |
55 | @Override
56 | public int compareTo(final DoubleInterval that) {
57 | final UnsupportedOperationException e = new UnsupportedOperationException(
58 | "Unimplemented method called: Number.compareTo");
59 | throw e;
60 | }
61 |
62 | @Override
63 | public DoubleInterval copy() {
64 | return valueOf(_lower, _upper);
65 | }
66 |
67 | @Override
68 | public double doubleValue() {
69 | return (_lower + _upper) / 2;
70 | }
71 |
72 | @Override
73 | public long longValue() {
74 | return (long) doubleValue();
75 | }
76 |
77 | public DoubleInterval times(final DoubleInterval that) {
78 | final double _l1 = _lower * that._lower;
79 | final double _l2 = _lower * that._upper;
80 | final double _l3 = _upper * that._lower;
81 | final double _l4 = _upper * that._upper;
82 | return outward(StrictMath.min(StrictMath.min(_l1, _l2), StrictMath.min(_l3, _l4)), StrictMath.max(
83 | StrictMath.max(_l1, _l2), StrictMath.max(_l3, _l4)));
84 | }
85 |
86 | public DoubleInterval opposite() {
87 | return valueOf(-_upper, -_lower);
88 | }
89 |
90 | public DoubleInterval plus(final DoubleInterval that) {
91 | return outward(_lower + that._lower, _upper + that._upper);
92 | }
93 |
94 | public boolean contains(final double d) {
95 | return _lower <= d && d <= _upper;
96 | }
97 |
98 | /** The multiplicative inverse. */
99 | public DoubleInterval inverse() {
100 | DoubleInterval res;
101 | if (contains(0)) res = NaN;
102 | else res = outward(1 / _upper, 1 / _lower);
103 | return res;
104 | }
105 |
106 | public DoubleInterval divide(final DoubleInterval that) {
107 | return times(that.inverse());
108 | }
109 |
110 | @Override
111 | public DoubleInterval abs() {
112 | DoubleInterval res;
113 | if (contains(0)) res = valueOf(0, StrictMath.max(-_lower, _upper));
114 | else res = this;
115 | return res;
116 | }
117 |
118 | public DoubleInterval min(final DoubleInterval that) {
119 | return valueOf(StrictMath.min(_lower, that._lower), StrictMath.min(_upper, that._upper));
120 | }
121 |
122 | public DoubleInterval max(final DoubleInterval that) {
123 | return valueOf(StrictMath.max(_lower, that._lower), StrictMath.max(_upper, that._upper));
124 | }
125 |
126 | @Override
127 | public BigDecimal decimalValue() {
128 | return BigDecimal.valueOf(doubleValue());
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/util/AbstractJavolutionJUnitAdapter.java:
--------------------------------------------------------------------------------
1 | package org.jscience.util;
2 |
3 | import org.junit.Before;
4 |
5 | import javolution.testing.JUnitContext;
6 | import javolution.testing.TestCase;
7 | import javolution.testing.TestContext;
8 |
9 | import static javolution.testing.TestContext.*;
10 |
11 | public abstract class AbstractJavolutionJUnitAdapter extends junit.framework.TestCase {
12 |
13 | @Override
14 | protected void setUp() throws Exception {
15 | super.setUp();
16 | JUnitContext.enter();
17 | }
18 |
19 | /** Feeds the test to the {@link TestContext}. This method is here to provide a hook to do other things here. */
20 | protected void doTest(final TestCase test) {
21 | try {
22 | TestContext.run(test);
23 | } catch (Throwable e) {
24 | // try { // for easier debugging a retry
25 | // test.setUp();
26 | // test.execute();
27 | // test.validate();
28 | // test.tearDown();
29 | // } catch (Exception e2) {}
30 | e.printStackTrace();
31 | if (e instanceof Error) throw (Error) e;
32 | if (e instanceof RuntimeException) throw (RuntimeException) e;
33 | throw new RuntimeException(e);
34 | }
35 | }
36 |
37 | @Override
38 | protected void tearDown() throws Exception {
39 | super.tearDown();
40 | JUnitContext.exit();
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/util/AbstractTestSuite.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2007 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.util;
10 |
11 | import static javolution.context.LogContext.info;
12 |
13 | import java.lang.reflect.InvocationTargetException;
14 | import java.lang.reflect.Method;
15 | import java.util.List;
16 | import java.util.Map;
17 | import java.util.TreeMap;
18 |
19 | import org.junit.After;
20 | import org.junit.Before;
21 | import org.junit.Test;
22 |
23 | import javolution.testing.JUnitContext;
24 | import javolution.testing.TestCase;
25 | import javolution.testing.TestContext;
26 | import javolution.testing.TestSuite;
27 |
28 | /**
29 | * Base class for test suites that run all methods starting with "test" to create the actual tests. This is makes sense
30 | * if there are many tests - so one cannot forget to call any of them. A free JUnit-Adapter is also included. :-)
31 | * @since 22.12.2008
32 | * @author Hans-Peter Störr
33 | */
34 | public abstract class AbstractTestSuite extends TestSuite {
35 |
36 | private boolean initialized = false;
37 |
38 | @Override
39 | public void setUp() {
40 | super.setUp();
41 | if (!initialized) {
42 | runTestCreatorMethods();
43 | initialized = true;
44 | }
45 | }
46 |
47 | /**
48 | * Runs all methods of this class that start with "test" by reflection. All methods starting with "test" must have
49 | * noarguments.
50 | */
51 | private void runTestCreatorMethods() {
52 | final Map testMethods = new TreeMap();
53 | Class> clazz = getClass();
54 | while (null != clazz) {
55 | for (final Method m : clazz.getDeclaredMethods()) {
56 | final String name = m.getName();
57 | if (name.startsWith("test") && !name.equals("tests") && !testMethods.containsKey(name))
58 | testMethods.put(name, m);
59 | }
60 | clazz = clazz.getSuperclass();
61 | }
62 | for (final Map.Entry e : testMethods.entrySet())
63 | try {
64 | info(getClass() + " invoking " + e.getValue());
65 | e.getValue().invoke(this);
66 | } catch (final IllegalAccessException e1) {
67 | throw new RuntimeException(e1.toString(), e1);
68 | } catch (final InvocationTargetException e1) {
69 | throw new RuntimeException(e1.toString(), e1.getTargetException());
70 | }
71 | }
72 |
73 | /** Gives the test to the {@link TestContext}. This method is here to provide a hook to do other things here. */
74 | protected void doTest(final TestCase t) {
75 | addTest(t);
76 | }
77 |
78 | @Test
79 | public void runTests() throws Exception {
80 | JUnitContext.enter();
81 | try {
82 | TestContext.run(this);
83 | } finally {
84 | JUnitContext.exit();
85 | }
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/mathematics/src/test/java/org/jscience/util/Pair.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2007 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.util;
10 |
11 | /**
12 | * A simple helper class that holds an immutable pair of objects.
13 | * @author Hans-Peter Störr
14 | * @since 11.12.2008
15 | * @param the type of the first object
16 | * @param the type of the second object
17 | */
18 | public final class Pair {
19 |
20 | /** The first object. */
21 | public final T1 _x;
22 |
23 | /** The second object. */
24 | public final T2 _y;
25 |
26 | /** Please use {@link #make(Object, Object)}. */
27 | private Pair(T1 x, T2 y) {
28 | _x = x;
29 | _y = y;
30 | }
31 |
32 | /** Constructs a {@link Pair} of objects: use for instance as Pair.make(14,"foo"). */
33 | public static Pair make(T1 x, T2 y) {
34 | return new Pair(x, y);
35 | }
36 |
37 | /**
38 | * A string representation for debugging purposes. For instance {14,foo}.
39 | * @see java.lang.Object#toString()
40 | */
41 | @Override
42 | public String toString() {
43 | return "{" + _x + "," + _y + "}";
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/physics/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 |
5 |
6 |
7 |
8 | org.jscience
9 | jscience
10 | 5.0.0-SNAPSHOT
11 |
12 | jscience-physics
13 | 5.0.0-SNAPSHOT
14 | JScience Physics Bundle
15 | bundle
16 |
17 |
18 |
19 |
20 |
21 |
22 | org.jscience
23 | jscience-mathematics
24 | ${version}
25 |
26 |
27 |
28 |
29 |
30 |
31 | org.unitsofmeasurement
32 | unit-api
33 | 0.6.1
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 | org.apache.felix
44 | maven-bundle-plugin
45 | 2.3.7
46 | true
47 |
48 |
49 | !org.jscience.physics.internal.*,org.jscience.physics.*
50 | org.jscience.physics.internal.*
51 | org.jscience.physics.internal.osgi.BundleActivatorImpl
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/amount/Amount.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2006 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.amount;
10 |
11 | import org.jscience.mathematics.number.NumberField;
12 | import org.jscience.mathematics.structure.Field;
13 | import org.unitsofmeasurement.quantity.Quantity;
14 | import org.unitsofmeasurement.unit.Unit;
15 |
16 | /**
17 | *
A determinate or estimated amount for which operations such as addition,
18 | * subtraction, multiplication and division can be performed (it implements
19 | * the {@link Field} interface).
20 | *
The nature of an amount can be deduced from its parameterization type
21 | * (compile time) or its unit (run time).
22 | * [code]
23 | * // Amount equivalent to the primitive type {@code double} but of mass nature.
24 | * Amount weight = Amount.of(3.4, KILOGRAM);
25 | *
26 | * // Exact amount.
27 | * Amount length = Amount.of(Rational.of(33, 1), FOOT);
28 | *
29 | * // Arbitrary precision amount (here dimensionless).
30 | * Amount π = Amount.of(Real.of("3.14 ± 0.01"));
31 | *
32 | * // Complex amount.
33 | * Amount, Current> Ψ = Amounts.of(Complex.of(2.3, 5.6), AMPERE);
34 | *
35 | * // Amount vectors (all vector's elements share the same unit).
36 | * AmountVector velocity3D = AmountVector.of(METER_PER_SECOND, 1.2, 3.4 -5.7);
37 | *
38 | * // Vector of heterogeneous amounts (each vector's elements has its own unit).
39 | * Vector> V0 = Vector.of(weight, duration); // See Vectors class.
40 | *
41 | * // etc...
42 | * [/code]
43 | *
44 | * @author Jean-Marie Dautelle
45 | * @version 5.0, January 26, 2014
46 | * @see
47 | * Wikipedia: Measuring
48 | */
49 | public abstract class Amount, Q extends Quantity>
50 | implements Field> {
51 |
52 | /**
53 | * Returns the value of this amount stated in this amount {@link #getUnit unit}.
54 | */
55 | public abstract N value();
56 |
57 | /**
58 | * Returns the unit identifying the nature of this amount.
59 | */
60 | public abstract Unit unit();
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/amount/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 |
Provides support for exact or arbitrary precision measurements.
3 | Provides physical quantities of any measurable type.
4 | */
5 | package org.jscience.physics.amount;
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/dimension/PhysicsDimensionService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.dimension;
10 |
11 | import org.unitsofmeasurement.quantity.Quantity;
12 |
13 | /**
14 | *
This interface represents the service to retrieve the dimension
15 | * given a quantity type.
16 | *
17 | *
Bundles providing new quantity types and/or dimensions should publish
18 | * instances of this class in order for the framework to be able
19 | * to determinate the dimension associated to the new quantities.
20 | *
21 | *
When activated the jscience-physics bundle publishes the dimensional
22 | * mapping of all quantities defined in the
23 | * org.unitsofmeasurement.quantity package.
24 |
25 | *
Published instances are typically used to check the dimensional
26 | * consistency of physical quantities.
27 | *
28 | * @author Jean-Marie Dautelle
29 | * @version 5.0, October 27, 2011
30 | */
31 | public interface PhysicsDimensionService {
32 |
33 | /**
34 | * Returns the dimension for the specified quantity or null if
35 | * unknown.
36 | *
37 | * @return the corresponding dimension or null
38 | */
39 | > PhysicsDimension getDimension(Class quantityType);
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/dimension/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | This package provides support for Dimensional Analysis.
3 |
4 |
The difference between dimensional models lies in the assumptions each makes and,
5 | in consequence,the operations each permits. For example, the summation
6 | of a {@link org.unitsofmeasurement.quantity.Length length} and a {@link org.unitsofmeasurement.quantity.Duration duration}
7 | is not allowed by the standard model, but is quite valid in a relativistic context.
8 |
9 |
Models are {@link javolution.context.LocalContext context-local}, allowing
10 | multiple models to be used concurrently. For example:[code]
11 | LocalContext.enter();
12 | try {
13 | RelativisticModel.select(); // Affects the current thread only.
14 | ...
15 | } finally {
16 | LocalContext.exit();
17 | }[/code]
18 |
19 |
The names and characteristics of the models are presented in the following table:
118 | **/
119 | package org.jscience.physics.dimension;
120 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/internal/osgi/BundleActivatorImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.internal.osgi;
10 |
11 | import javolution.context.LogContext;
12 | import org.osgi.framework.BundleActivator;
13 | import org.osgi.framework.BundleContext;
14 | import org.osgi.framework.Constants;
15 | import org.unitsofmeasurement.service.SystemOfUnitsService;
16 | import org.unitsofmeasurement.service.UnitFormatService;
17 |
18 | /**
19 | *
The OSGi activator for the jscience-physics bundle.
20 | *
21 | * @author Jean-Marie Dautelle
22 | * @version 5.0, October 21, 2011
23 | */
24 | public class BundleActivatorImpl implements BundleActivator {
25 |
26 | public void start(BundleContext bc) throws Exception {
27 | Object name = bc.getBundle().getHeaders().get(Constants.BUNDLE_NAME);
28 | Object version = bc.getBundle().getHeaders().get(Constants.BUNDLE_VERSION);
29 | LogContext.info("Start Bundle: ", name, ", Version: ", version);
30 |
31 | // Publish SystemOfUnitsServices Implementation.
32 | bc.registerService(SystemOfUnitsService.class.getName(), new SystemOfUnitsServiceImpl(), null);
33 |
34 | // Publish UnitFormatService Implementation.
35 | bc.registerService(UnitFormatService.class.getName(), new UnitFormatServiceImpl(), null);
36 |
37 | }
38 |
39 | public void stop(BundleContext bc) throws Exception {
40 | Object name = bc.getBundle().getHeaders().get(Constants.BUNDLE_NAME);
41 | Object version = bc.getBundle().getHeaders().get(Constants.BUNDLE_VERSION);
42 | LogContext.info("Stop Bundle: ", name, ", Version: ", version);
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/internal/osgi/SystemOfUnitsServiceImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.internal.osgi;
10 |
11 | import org.jscience.physics.unit.SI;
12 | import org.jscience.physics.unit.UCUM;
13 | import org.unitsofmeasurement.service.SystemOfUnitsService;
14 | import org.unitsofmeasurement.unit.SystemOfUnits;
15 |
16 | /**
17 | * SystemOfUnitsService Implementation.
18 | */
19 | class SystemOfUnitsServiceImpl implements SystemOfUnitsService {
20 |
21 | /**
22 | * Returns the SI instance.
23 | */
24 | public SystemOfUnits getSystemOfUnits() {
25 | return SI.getInstance();
26 | }
27 |
28 | /**
29 | * Returns the instance having the specified name.
30 | */
31 | public SystemOfUnits getSystemOfUnits(String name) {
32 | if (name.equals("SI")) return SI.getInstance();
33 | if (name.equals("UCUM")) return UCUM.getInstance();
34 | return null;
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/internal/osgi/UnitFormatServiceImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.internal.osgi;
10 |
11 | import java.util.Locale;
12 | import org.jscience.physics.unit.formats.LocalUnitFormat;
13 | import org.jscience.physics.unit.formats.UCUMFormat;
14 | import org.unitsofmeasurement.service.UnitFormatService;
15 | import org.unitsofmeasurement.unit.UnitFormat;
16 |
17 | /**
18 | * UnitFormatService Implementation.
19 | */
20 | class UnitFormatServiceImpl implements UnitFormatService {
21 |
22 | /**
23 | * Returns the UCUM instance.
24 | */
25 | public UnitFormat getUnitFormat() {
26 | return UCUMFormat.getCaseSensitiveInstance();
27 | }
28 |
29 | /**
30 | * Returns the format having the specified name.
31 | */
32 | public UnitFormat getUnitFormat(String name) {
33 | if (name.equals("UCUM")) return UCUMFormat.getCaseSensitiveInstance();
34 | return null;
35 | }
36 |
37 | /**
38 | * Returns the format for the specified locale.
39 | */
40 | public UnitFormat getUnitFormat(Locale locale) {
41 | return LocalUnitFormat.getInstance(locale);
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/internal/unit/format/UCUMParserConstants.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | /* Generated By:JavaCC: Do not edit this line. UCUMParserConstants.java */
10 | package org.jscience.physics.internal.unit.format;
11 |
12 |
13 | /**
14 | * Token literal values and constants.
15 | * Generated by org.javacc.parser.OtherFilesGen#start()
16 | */
17 | public interface UCUMParserConstants {
18 |
19 | /** End of File. */
20 | int EOF = 0;
21 | /** RegularExpression Id. */
22 | int ATOM_CHAR = 1;
23 | /** RegularExpression Id. */
24 | int ESCAPED_ATOM_CHAR = 2;
25 | /** RegularExpression Id. */
26 | int TERMINAL_ATOM_CHAR = 3;
27 | /** RegularExpression Id. */
28 | int LCBRACKET = 4;
29 | /** RegularExpression Id. */
30 | int RCBRACKET = 5;
31 | /** RegularExpression Id. */
32 | int LSBRACKET = 6;
33 | /** RegularExpression Id. */
34 | int RSBRACKET = 7;
35 | /** RegularExpression Id. */
36 | int ANNOTATION = 8;
37 | /** RegularExpression Id. */
38 | int FACTOR = 9;
39 | /** RegularExpression Id. */
40 | int SIGN = 10;
41 | /** RegularExpression Id. */
42 | int DOT = 11;
43 | /** RegularExpression Id. */
44 | int SOLIDUS = 12;
45 | /** RegularExpression Id. */
46 | int ATOM = 13;
47 |
48 | /** Lexical state. */
49 | int DEFAULT = 0;
50 |
51 | /** Literal token values. */
52 | String[] tokenImage = {
53 | "",
54 | "",
55 | "",
56 | "",
57 | "\"{\"",
58 | "\"}\"",
59 | "\"[\"",
60 | "\"]\"",
61 | "",
62 | "",
63 | "",
64 | "\".\"",
65 | "\"/\"",
66 | "",
67 | "\"(\"",
68 | "\")\"",
69 | };
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/internal/unit/format/UnitParserConstants.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | /* Generated By:JavaCC: Do not edit this line. UnitParserConstants.java */
10 | package org.jscience.physics.internal.unit.format;
11 |
12 |
13 | /**
14 | * Token literal values and constants.
15 | * Generated by org.javacc.parser.OtherFilesGen#start()
16 | */
17 | public interface UnitParserConstants {
18 |
19 | /** End of File. */
20 | int EOF = 0;
21 | /** RegularExpression Id. */
22 | int DIGIT = 1;
23 | /** RegularExpression Id. */
24 | int SUPERSCRIPT_DIGIT = 2;
25 | /** RegularExpression Id. */
26 | int INITIAL_CHAR = 3;
27 | /** RegularExpression Id. */
28 | int EXTENDED_CHAR = 4;
29 | /** RegularExpression Id. */
30 | int PLUS = 5;
31 | /** RegularExpression Id. */
32 | int MINUS = 6;
33 | /** RegularExpression Id. */
34 | int ASTERISK = 7;
35 | /** RegularExpression Id. */
36 | int MIDDLE_DOT = 8;
37 | /** RegularExpression Id. */
38 | int SOLIDUS = 9;
39 | /** RegularExpression Id. */
40 | int CARET = 10;
41 | /** RegularExpression Id. */
42 | int COLON = 11;
43 | /** RegularExpression Id. */
44 | int OPEN_PAREN = 12;
45 | /** RegularExpression Id. */
46 | int CLOSE_PAREN = 13;
47 | /** RegularExpression Id. */
48 | int INTEGER = 14;
49 | /** RegularExpression Id. */
50 | int SUPERSCRIPT_INTEGER = 15;
51 | /** RegularExpression Id. */
52 | int FLOATING_POINT = 16;
53 | /** RegularExpression Id. */
54 | int LOG = 17;
55 | /** RegularExpression Id. */
56 | int NAT_LOG = 18;
57 | /** RegularExpression Id. */
58 | int E = 19;
59 | /** RegularExpression Id. */
60 | int UNIT_IDENTIFIER = 20;
61 |
62 | /** Lexical state. */
63 | int DEFAULT = 0;
64 |
65 | /** Literal token values. */
66 | String[] tokenImage = {
67 | "",
68 | "",
69 | "",
70 | "",
71 | "",
72 | "\"+\"",
73 | "\"-\"",
74 | "\"*\"",
75 | "\"\\u00b7\"",
76 | "\"/\"",
77 | "\"^\"",
78 | "\":\"",
79 | "\"(\"",
80 | "\")\"",
81 | "",
82 | "",
83 | "",
84 | "",
85 | "",
86 | "\"e\"",
87 | "",
88 | };
89 |
90 | }
91 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/model/HighEnergyModel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.model;
10 |
11 | /**
12 | * This class represents the high-energy model.
13 | *
14 | * @author Jean-Marie Dautelle
15 | * @version 5.0, October 12, 2010
16 | */
17 | public class HighEnergyModel extends RelativisticModel {
18 |
19 |
20 | /**
21 | * Default constructor.
22 | */
23 | public HighEnergyModel() {
24 | }
25 |
26 | // TODO: Allow more conversion.
27 | // // SPEED_OF_LIGHT (METRE / SECOND) = 1
28 | // SI.SECOND.setDimension(SI.NANO(SI.SECOND), new MultiplyConverter(1E9));
29 | // SI.METRE.setDimension(SI.NANO(SI.SECOND),
30 | // new MultiplyConverter(1E9 / c));
31 | //
32 | // // ENERGY = m²·kg/s² = kg·c²
33 | // SI.KILOGRAM.setDimension(SI.GIGA(NonSI.ELECTRON_VOLT),
34 | // new MultiplyConverter(c * c / ePlus / 1E9));
35 | //
36 | // // BOLTZMANN (JOULE / KELVIN = (KILOGRAM / C^2 ) / KELVIN) = 1
37 | // SI.KELVIN.setDimension(SI.GIGA(NonSI.ELECTRON_VOLT),
38 | // new MultiplyConverter(k / ePlus / 1E9));
39 | //
40 | // // ELEMENTARY_CHARGE (SECOND * AMPERE) = 1
41 | // SI.AMPERE.setDimension(Unit.ONE.divide(SI.NANO(SI.SECOND)),
42 | // new MultiplyConverter(1E-9 / ePlus));
43 | //
44 | // SI.MOLE.setDimension(SI.MOLE, Converter.IDENTITY);
45 | // SI.CANDELA.setDimension(SI.CANDELA, Converter.IDENTITY);
46 |
47 | }
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/model/NaturalModel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.model;
10 |
11 | /**
12 | * This class represents the natural model.
13 | *
14 | * @see
15 | * Wikipedia: Planck units
16 | * @author Jean-Marie Dautelle
17 | * @version 5.0, October 12, 2010
18 | */
19 | public class NaturalModel extends QuantumModel {
20 |
21 |
22 | /**
23 | * Default constructor.
24 | */
25 | public NaturalModel() {
26 | }
27 |
28 | // TODO: Allow more conversion.
29 | // // H_BAR (SECOND * JOULE = SECOND * (KILOGRAM / C^2 )) = 1
30 | // // SPEED_OF_LIGHT (METRE / SECOND) = 1
31 | // // BOLTZMANN (JOULE / KELVIN = (KILOGRAM / C^2 ) / KELVIN) = 1
32 | // // MAGNETIC CONSTANT (NEWTON / AMPERE^2) = 1
33 | // // GRAVITATIONAL CONSTANT (METRE^3 / KILOGRAM / SECOND^2) = 1
34 | // SI.SECOND.setDimension(NONE, new MultiplyConverter((c * c)
35 | // * MathLib.sqrt(c / (hBar * G))));
36 | // SI.METRE.setDimension(NONE, new MultiplyConverter(c
37 | // * MathLib.sqrt(c / (hBar * G))));
38 | // SI.KILOGRAM.setDimension(NONE, new MultiplyConverter(MathLib.sqrt(G
39 | // / (hBar * c))));
40 | // SI.KELVIN.setDimension(NONE, new MultiplyConverter(k
41 | // * MathLib.sqrt(G / (hBar * c)) / (c * c)));
42 | // SI.AMPERE.setDimension(NONE, new MultiplyConverter(MathLib.sqrt(µ0 * G)
43 | // / (c * c)));
44 | // SI.MOLE.setDimension(AMOUNT_OF_SUBSTANCE, Converter.IDENTITY);
45 | // SI.CANDELA.setDimension(LUMINOUS_INTENSITY, Converter.IDENTITY);
46 | }
47 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/model/QuantumModel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.model;
10 |
11 | /**
12 | * This class represents the quantum model.
13 | *
14 | * @author Jean-Marie Dautelle
15 | * @version 5.0, October 12, 2010
16 | */
17 | public class QuantumModel extends HighEnergyModel {
18 |
19 | /**
20 | * Default constructor.
21 | */
22 | public QuantumModel() {
23 | }
24 |
25 | // TODO: Allow more conversion.
26 | // // ENERGY = m²·kg/s² = kg·c²
27 | // SI.KILOGRAM.setDimension(SI.GIGA(NonSI.ELECTRON_VOLT),
28 | // new MultiplyConverter(1E-9 * c * c / ePlus));
29 | //
30 | // // H_BAR (SECOND * JOULE = SECOND * (KILOGRAM / C^2 )) = 1
31 | // SI.SECOND.setDimension(Unit.ONE.divide(SI.GIGA(NonSI.ELECTRON_VOLT)),
32 | // new MultiplyConverter(1E9 * ePlus / hBar));
33 | //
34 | // // SPEED_OF_LIGHT (METRE / SECOND) = 1
35 | // SI.METRE.setDimension(Unit.ONE.divide(SI.GIGA(NonSI.ELECTRON_VOLT)),
36 | // new MultiplyConverter(1E9 * ePlus / (c * hBar)));
37 | //
38 | // // BOLTZMANN (JOULE / KELVIN = (KILOGRAM / C^2 ) / KELVIN) = 1
39 | // SI.KELVIN.setDimension(SI.GIGA(NonSI.ELECTRON_VOLT),
40 | // new MultiplyConverter(1E-9 * k / ePlus));
41 | //
42 | // // MAGNETIC CONSTANT (NEWTON / AMPERE^2) = 1
43 | // SI.AMPERE.setDimension(SI.GIGA(NonSI.ELECTRON_VOLT),
44 | // new MultiplyConverter(1E-9 * MathLib.sqrt(µ0 * c * hBar) / ePlus));
45 | //
46 | // SI.MOLE.setDimension(SI.MOLE, Converter.IDENTITY);
47 | // SI.CANDELA.setDimension(SI.CANDELA, Converter.IDENTITY);
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/model/RelativisticModel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.model;
10 |
11 | import org.jscience.physics.dimension.PhysicsDimension;
12 | import org.jscience.physics.unit.PhysicsConverter;
13 | import org.jscience.physics.unit.converters.RationalConverter;
14 |
15 | /**
16 | * This class represents the relativistic model.
17 | *
18 | * @author Jean-Marie Dautelle
19 | * @version 5.0, October 12, 2010
20 | */
21 | public class RelativisticModel extends StandardModel {
22 |
23 | /**
24 | * Holds the meter to time transform.
25 | */
26 | private static RationalConverter METRE_TO_TIME
27 | = new RationalConverter(1, 299792458);
28 |
29 | /**
30 | * Default constructor.
31 | */
32 | public RelativisticModel() {
33 | }
34 |
35 | @Override
36 | public PhysicsDimension getFundamentalDimension(PhysicsDimension dimension) {
37 | if (dimension.equals(PhysicsDimension.LENGTH)) return PhysicsDimension.TIME;
38 | return super.getFundamentalDimension(dimension);
39 | }
40 |
41 | @Override
42 | public PhysicsConverter getDimensionalTransform(PhysicsDimension dimension) {
43 | if (dimension.equals(PhysicsDimension.LENGTH)) return METRE_TO_TIME;
44 | return super.getDimensionalTransform(dimension);
45 | }
46 |
47 | }
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/model/StandardModel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.model;
10 |
11 | import org.jscience.physics.dimension.DimensionalModel;
12 |
13 | /**
14 | * This class represents the standard model.
15 | *
16 | * @author Jean-Marie Dautelle
17 | * @version 5.0, October 12, 2010
18 | */
19 | public class StandardModel extends DimensionalModel {
20 |
21 | /**
22 | * Default constructor.
23 | */
24 | public StandardModel() {
25 | }
26 |
27 | }
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/unit/BinaryPrefix.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.unit;
10 |
11 | import org.unitsofmeasurement.unit.Unit;
12 | import org.unitsofmeasurement.quantity.Quantity;
13 |
14 | /**
15 | *
This class provides support for common binary prefixes to be used by
16 | * units.
17 | *
18 | * @author Werner Keil
19 | * @version 5.0, October 12, 2010
20 | */
21 | public final class BinaryPrefix {
22 |
23 | /**
24 | * Default constructor (private).
25 | */
26 | private BinaryPrefix() {
27 | // Utility class no visible constructor.
28 | }
29 |
30 | /**
31 | * Returns the specified unit multiplied by the factor
32 | * 210 (binary prefix).
33 | *
34 | * @param unit any unit.
35 | * @return unit.times(1024).
36 | */
37 | public static > Unit KIBI(Unit unit) {
38 | return unit.multiply(1024);
39 | }
40 |
41 | /**
42 | * Returns the specified unit multiplied by the factor
43 | * 220 (binary prefix).
44 | *
45 | * @param unit any unit.
46 | * @return unit.times(1048576).
47 | */
48 | public static > Unit MEBI(Unit unit) {
49 | return unit.multiply(1048576);
50 | }
51 |
52 | /**
53 | * Returns the specified unit multiplied by the factor
54 | * 230 (binary prefix).
55 | *
56 | * @param unit any unit.
57 | * @return unit.times(1073741824).
58 | */
59 | public static > Unit GIBI(Unit unit) {
60 | return unit.multiply(1073741824);
61 | }
62 |
63 | /**
64 | * Returns the specified unit multiplied by the factor
65 | * 240 (binary prefix).
66 | *
67 | * @param unit any unit.
68 | * @return unit.times(1099511627776L).
69 | */
70 | public static > Unit TEBI(Unit unit) {
71 | return unit.multiply(1099511627776L);
72 | }
73 |
74 | /**
75 | * Returns the specified unit multiplied by the factor
76 | * 250 (binary prefix).
77 | *
78 | * @param unit any unit.
79 | * @return unit.times(1125899906842624L).
80 | */
81 | public static > Unit PEBI(Unit unit) {
82 | return unit.multiply(1125899906842624L);
83 | }
84 |
85 | /**
86 | * Returns the specified unit multiplied by the factor
87 | * 260 (binary prefix).
88 | *
89 | * @param unit any unit.
90 | * @return unit.times(1152921504606846976L).
91 | */
92 | public static > Unit EXBI(Unit unit) {
93 | return unit.multiply(1152921504606846976L);
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/unit/converters/AddConverter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.unit.converters;
10 |
11 | import org.jscience.physics.unit.PhysicsConverter;
12 | import java.math.BigDecimal;
13 | import java.math.MathContext;
14 | import javolution.lang.Immutable;
15 | import org.unitsofmeasurement.unit.UnitConverter;
16 |
17 | /**
18 | *
This class represents a converter adding a constant offset
19 | * to numeric values (double based).
20 | *
21 | * @author Jean-Marie Dautelle
22 | * @version 5.0, October 12, 2010
23 | */
24 | public final class AddConverter extends PhysicsConverter implements Immutable {
25 |
26 | /**
27 | * Holds the offset.
28 | */
29 | private double offset;
30 |
31 | /**
32 | * Creates an additive converter having the specified offset.
33 | *
34 | * @param offset the offset value.
35 | * @throws IllegalArgumentException if offset is 0.0
36 | * (would result in identity converter).
37 | */
38 | public AddConverter(double offset) {
39 | if (offset == 0.0)
40 | throw new IllegalArgumentException("Would result in identity converter");
41 | this.offset = offset;
42 | }
43 |
44 | /**
45 | * Returns the offset value for this add converter.
46 | *
47 | * @return the offset value.
48 | */
49 | public double getOffset() {
50 | return offset;
51 | }
52 |
53 | @Override
54 | public UnitConverter concatenate(UnitConverter converter) {
55 | if (!(converter instanceof AddConverter))
56 | return super.concatenate(converter);
57 | double newOffset = offset + ((AddConverter) converter).offset;
58 | return newOffset == 0.0 ? IDENTITY : new AddConverter(newOffset);
59 | }
60 |
61 | @Override
62 | public AddConverter inverse() {
63 | return new AddConverter(-offset);
64 | }
65 |
66 | @Override
67 | public double convert(double value) {
68 | return value + offset;
69 | }
70 |
71 | @Override
72 | public BigDecimal convert(BigDecimal value, MathContext ctx) throws ArithmeticException {
73 | return value.add(BigDecimal.valueOf(offset), ctx);
74 | }
75 |
76 | @Override
77 | public final String toString() {
78 | return "AddConverter(" + offset + ")";
79 | }
80 |
81 | @Override
82 | public boolean equals(Object obj) {
83 | if (!(obj instanceof AddConverter)) {
84 | return false;
85 | }
86 | AddConverter that = (AddConverter) obj;
87 | return this.offset == that.offset;
88 | }
89 |
90 | @Override
91 | public int hashCode() {
92 | long bits = Double.doubleToLongBits(offset);
93 | return (int) (bits ^ (bits >>> 32));
94 | }
95 |
96 | @Override
97 | public boolean isLinear() {
98 | return false;
99 | }
100 |
101 | }
102 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/unit/converters/ExpConverter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.unit.converters;
10 |
11 | import org.jscience.physics.unit.PhysicsConverter;
12 | import java.math.BigDecimal;
13 | import java.math.MathContext;
14 | import javolution.lang.Immutable;
15 |
16 | /**
17 | *
This class represents a exponential converter of limited precision.
18 | * Such converter is used to create inverse of logarithmic unit.
19 | *
20 | *
This class is package private, instances are created
21 | * using the {@link LogConverter#inverse()} method.
22 | *
23 | * @author Jean-Marie Dautelle
24 | * @version 5.0, October 12, 2010
25 | */
26 | final class ExpConverter extends PhysicsConverter implements Immutable {
27 |
28 | /**
29 | * Holds the logarithmic base.
30 | */
31 | private double base;
32 |
33 | /**
34 | * Holds the natural logarithm of the base.
35 | */
36 | private double logOfBase;
37 |
38 | /**
39 | * Creates a logarithmic converter having the specified base.
40 | *
41 | * @param base the logarithmic base (e.g. Math.E for
42 | * the Natural Logarithm).
43 | */
44 | public ExpConverter(double base) {
45 | this.base = base;
46 | this.logOfBase = Math.log(base);
47 | }
48 |
49 | /**
50 | * Returns the exponential base of this converter.
51 | *
52 | * @return the exponential base (e.g. Math.E for
53 | * the Natural Exponential).
54 | */
55 | public double getBase() {
56 | return base;
57 | }
58 |
59 | @Override
60 | public PhysicsConverter inverse() {
61 | return new LogConverter(base);
62 | }
63 |
64 | @Override
65 | public final String toString() {
66 | if (base == Math.E) {
67 | return "e";
68 | } else {
69 | return "Exp(" + base + ")";
70 | }
71 | }
72 |
73 | @Override
74 | public boolean equals(Object obj) {
75 | if (!(obj instanceof ExpConverter))
76 | return false;
77 | ExpConverter that = (ExpConverter) obj;
78 | return this.base == that.base;
79 | }
80 |
81 | @Override
82 | public int hashCode() {
83 | long bits = Double.doubleToLongBits(base);
84 | return (int) (bits ^ (bits >>> 32));
85 | }
86 |
87 | @Override
88 | public double convert(double amount) {
89 | return Math.exp(logOfBase * amount);
90 | }
91 |
92 | @Override
93 | public BigDecimal convert(BigDecimal value, MathContext ctx) throws ArithmeticException {
94 | return BigDecimal.valueOf(convert(value.doubleValue())); // Reverts to double conversion.
95 | }
96 |
97 | @Override
98 | public boolean isLinear() {
99 | return false;
100 | }
101 |
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/unit/converters/LogConverter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.unit.converters;
10 |
11 | import org.jscience.physics.unit.PhysicsConverter;
12 | import java.math.BigDecimal;
13 | import java.math.MathContext;
14 | import javolution.lang.Immutable;
15 |
16 | /**
17 | *
This class represents a logarithmic converter of limited precision.
18 | * Such converter is typically used to create logarithmic unit.
19 | * For example:[code]
20 | * Unit BEL = Unit.ONE.transform(new LogConverter(10).inverse());
21 | * [/code]
22 | *
23 | * @author Jean-Marie Dautelle
24 | * @version 5.0, October 12, 2010
25 | */
26 | public final class LogConverter extends PhysicsConverter implements Immutable {
27 |
28 | /**
29 | * Holds the logarithmic base.
30 | */
31 | private double base;
32 | /**
33 | * Holds the natural logarithm of the base.
34 | */
35 | private double logOfBase;
36 |
37 | /**
38 | * Returns a logarithmic converter having the specified base.
39 | *
40 | * @param base the logarithmic base (e.g. Math.E for
41 | * the Natural Logarithm).
42 | */
43 | public LogConverter(double base) {
44 | this.base = base;
45 | this.logOfBase = Math.log(base);
46 | }
47 |
48 | /**
49 | * Returns the logarithmic base of this converter.
50 | *
51 | * @return the logarithmic base (e.g. Math.E for
52 | * the Natural Logarithm).
53 | */
54 | public double getBase() {
55 | return base;
56 | }
57 |
58 | @Override
59 | public PhysicsConverter inverse() {
60 | return new ExpConverter(base);
61 | }
62 |
63 | @Override
64 | public final String toString() {
65 | if (base == Math.E) {
66 | return "ln";
67 | } else {
68 | return "Log(" + base + ")";
69 | }
70 | }
71 |
72 | @Override
73 | public boolean equals(Object obj) {
74 | if (!(obj instanceof LogConverter))
75 | return false;
76 | LogConverter that = (LogConverter) obj;
77 | return this.base == that.base;
78 | }
79 |
80 | @Override
81 | public int hashCode() {
82 | long bits = Double.doubleToLongBits(base);
83 | return (int) (bits ^ (bits >>> 32));
84 | }
85 |
86 | @Override
87 | public double convert(double amount) {
88 | return Math.log(amount) / logOfBase;
89 | }
90 |
91 | @Override
92 | public BigDecimal convert(BigDecimal value, MathContext ctx) throws ArithmeticException {
93 | return BigDecimal.valueOf(convert(value.doubleValue())); // Reverts to double conversion.
94 | }
95 |
96 | @Override
97 | public boolean isLinear() {
98 | return false;
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/unit/converters/MultiplyConverter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.unit.converters;
10 |
11 | import org.jscience.physics.unit.PhysicsConverter;
12 | import java.math.BigDecimal;
13 | import java.math.MathContext;
14 | import javolution.lang.Immutable;
15 | import org.unitsofmeasurement.unit.UnitConverter;
16 |
17 | /**
18 | *
This class represents a converter multiplying numeric values by a
19 | * constant scaling factor (double based).
20 | *
21 | * @author Jean-Marie Dautelle
22 | * @version 5.0, October 12, 2010
23 | */
24 | public final class MultiplyConverter extends PhysicsConverter implements Immutable {
25 |
26 | /**
27 | * Holds the scale factor.
28 | */
29 | private double factor;
30 |
31 | /**
32 | * Creates a multiply converter with the specified scale factor.
33 | *
34 | * @param factor the scaling factor.
35 | * @throws IllegalArgumentException if coefficient is 1.0
36 | * (would result in identity converter)
37 | */
38 | public MultiplyConverter(double factor) {
39 | if (factor == 1.0)
40 | throw new IllegalArgumentException("Would result in identity converter");
41 | this.factor = factor;
42 | }
43 |
44 | /**
45 | * Returns the scale factor of this converter.
46 | *
47 | * @return the scale factor.
48 | */
49 | public double getFactor() {
50 | return factor;
51 | }
52 |
53 | @Override
54 | public UnitConverter concatenate(UnitConverter converter) {
55 | if (!(converter instanceof MultiplyConverter))
56 | return super.concatenate(converter);
57 | double newfactor = factor * ((MultiplyConverter) converter).factor;
58 | return newfactor == 1.0 ? IDENTITY : new MultiplyConverter(newfactor);
59 | }
60 |
61 | @Override
62 | public MultiplyConverter inverse() {
63 | return new MultiplyConverter(1.0 / factor);
64 | }
65 |
66 | @Override
67 | public double convert(double value) {
68 | return value * factor;
69 | }
70 |
71 | @Override
72 | public BigDecimal convert(BigDecimal value, MathContext ctx) throws ArithmeticException {
73 | return value.multiply(BigDecimal.valueOf(factor), ctx);
74 | }
75 |
76 | @Override
77 | public final String toString() {
78 | return "MultiplyConverter(" + factor + ")";
79 | }
80 |
81 | @Override
82 | public boolean equals(Object obj) {
83 | if (!(obj instanceof MultiplyConverter))
84 | return false;
85 | MultiplyConverter that = (MultiplyConverter) obj;
86 | return this.factor == that.factor;
87 | }
88 |
89 | @Override
90 | public int hashCode() {
91 | long bits = Double.doubleToLongBits(factor);
92 | return (int) (bits ^ (bits >>> 32));
93 | }
94 |
95 | @Override
96 | public boolean isLinear() {
97 | return true;
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/unit/converters/PiDivisorConverter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.unit.converters;
10 |
11 | import org.jscience.physics.unit.PhysicsConverter;
12 | import java.math.BigDecimal;
13 | import java.math.MathContext;
14 | import javolution.lang.Immutable;
15 | import javolution.lang.MathLib;
16 |
17 | /**
18 | *
This class represents a converter dividing numeric values by π (Pi).
19 | *
20 | *
This class is package private, instances are created
21 | * using the {@link PiMultiplierConverter#inverse()} method.
22 | *
23 | * @author Jean-Marie Dautelle
24 | * @version 5.0, October 12, 2010
25 | */
26 | final class PiDivisorConverter extends PhysicsConverter implements Immutable {
27 |
28 | /**
29 | * Creates a Pi multiplier converter.
30 | */
31 | public PiDivisorConverter() {
32 | }
33 |
34 | @Override
35 | public double convert(double value) {
36 | return value / MathLib.PI;
37 | }
38 |
39 | @Override
40 | public BigDecimal convert(BigDecimal value, MathContext ctx) throws ArithmeticException {
41 | int nbrDigits = ctx.getPrecision();
42 | if (nbrDigits == 0) throw new ArithmeticException("Pi multiplication with unlimited precision");
43 | BigDecimal pi = PiMultiplierConverter.Pi.pi(nbrDigits);
44 | return value.divide(pi, ctx).scaleByPowerOfTen(nbrDigits-1);
45 | }
46 |
47 | @Override
48 | public PhysicsConverter inverse() {
49 | return new PiMultiplierConverter();
50 | }
51 |
52 | @Override
53 | public final String toString() {
54 | return "(1/π)";
55 | }
56 |
57 | @Override
58 | public boolean equals(Object obj) {
59 | return (obj instanceof PiDivisorConverter) ? true : false;
60 | }
61 |
62 | @Override
63 | public int hashCode() {
64 | return 0;
65 | }
66 |
67 | @Override
68 | public boolean isLinear() {
69 | return true;
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/unit/converters/PiMultiplierConverter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
3 | * Copyright (C) 2010 - JScience (http://jscience.org/)
4 | * All rights reserved.
5 | *
6 | * Permission to use, copy, modify, and distribute this software is
7 | * freely granted, provided that this notice is preserved.
8 | */
9 | package org.jscience.physics.unit.converters;
10 |
11 | import org.jscience.physics.unit.PhysicsConverter;
12 | import java.math.BigDecimal;
13 | import java.math.MathContext;
14 | import java.math.RoundingMode;
15 | import javolution.lang.Immutable;
16 | import javolution.lang.MathLib;
17 |
18 | /**
19 | *
This class represents a converter multiplying numeric values by π (Pi).
20 | *
21 | * @see Wikipedia: Pi
22 | * @author Jean-Marie Dautelle
23 | * @version 5.0, October 12, 2010
24 | */
25 | public final class PiMultiplierConverter extends PhysicsConverter implements Immutable {
26 |
27 | /**
28 | * Creates a Pi multiplier converter.
29 | */
30 | public PiMultiplierConverter() {
31 | }
32 |
33 | @Override
34 | public double convert(double value) {
35 | return value * MathLib.PI;
36 | }
37 |
38 | @Override
39 | public BigDecimal convert(BigDecimal value, MathContext ctx) throws ArithmeticException {
40 | int nbrDigits = ctx.getPrecision();
41 | if (nbrDigits == 0) throw new ArithmeticException("Pi multiplication with unlimited precision");
42 | BigDecimal pi = Pi.pi(nbrDigits);
43 | return value.multiply(pi, ctx).scaleByPowerOfTen(1-nbrDigits);
44 | }
45 |
46 | @Override
47 | public PhysicsConverter inverse() {
48 | return new PiDivisorConverter();
49 | }
50 |
51 | @Override
52 | public final String toString() {
53 | return "(π)";
54 | }
55 |
56 | @Override
57 | public boolean equals(Object obj) {
58 | return (obj instanceof PiMultiplierConverter) ? true : false;
59 | }
60 |
61 | @Override
62 | public int hashCode() {
63 | return 0;
64 | }
65 |
66 | @Override
67 | public boolean isLinear() {
68 | return true;
69 | }
70 |
71 | /**
72 | * Pi calculation with Machin's formula.
73 | *
74 | * @see Pi with Machin's formula
75 | *
76 | */
77 | static final class Pi {
78 |
79 | private Pi() {
80 | }
81 |
82 | public static BigDecimal pi(int numDigits) {
83 | int calcDigits = numDigits + 10;
84 | return FOUR.multiply((FOUR.multiply(arccot(FIVE, calcDigits))).subtract(arccot(TWO_THIRTY_NINE, calcDigits))).setScale(numDigits, RoundingMode.DOWN);
85 | }
86 |
87 | private static BigDecimal arccot(BigDecimal x, int numDigits) {
88 | BigDecimal unity = BigDecimal.ONE.setScale(numDigits, RoundingMode.DOWN);
89 | BigDecimal sum = unity.divide(x, RoundingMode.DOWN);
90 | BigDecimal xpower = new BigDecimal(sum.toString());
91 | BigDecimal term = null;
92 | boolean add = false;
93 | for (BigDecimal n = new BigDecimal("3"); term == null
94 | || !term.equals(BigDecimal.ZERO); n = n.add(TWO)) {
95 | xpower = xpower.divide(x.pow(2), RoundingMode.DOWN);
96 | term = xpower.divide(n, RoundingMode.DOWN);
97 | sum = add ? sum.add(term) : sum.subtract(term);
98 | add = !add;
99 | }
100 | return sum;
101 | }
102 | }
103 | private static final BigDecimal TWO = new BigDecimal("2");
104 |
105 | private static final BigDecimal FOUR = new BigDecimal("4");
106 |
107 | private static final BigDecimal FIVE = new BigDecimal("5");
108 |
109 | private static final BigDecimal TWO_THIRTY_NINE = new BigDecimal("239");
110 |
111 | }
112 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/unit/converters/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This package provides concrete implementations of the
3 | * {@link org.unitsofmeasurement.unit.UnitConverter} interface.
4 | */
5 | package org.jscience.physics.unit.converters;
6 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/unit/formats/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This package facilitates the creation of concrete implementations of
3 | * {@link org.unitsofmeasurement.unit.service.UnitformatService}.
4 | * Clients can also obtain concrete implementations from their OSGi bundle
5 | * context or service tracker.
6 | */
7 | package org.jscience.physics.unit.formats;
8 |
--------------------------------------------------------------------------------
/physics/src/main/java/org/jscience/physics/unit/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * This package provides supports for physics units, in conformity with the
3 | * Units of Measurement API.
4 | *
5 | *