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 javax.measure.converter; |
10 | |
11 | /** |
12 | * <p> This class represents a logarithmic converter. Such converter |
13 | * is typically used to create logarithmic unit. For example:[code] |
14 | * Unit<Dimensionless> BEL = Unit.ONE.transform(new LogConverter(10).inverse()); |
15 | * [/code]</p> |
16 | * |
17 | * <p> Instances of this class are immutable.</p> |
18 | * |
19 | * @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a> |
20 | * @version 3.1, April 22, 2006 |
21 | */ |
22 | public final class LogConverter extends UnitConverter { |
23 | |
24 | /** |
25 | * Holds the logarithmic base. |
26 | */ |
27 | private final double _base; |
28 | |
29 | /** |
30 | * Holds the natural logarithm of the base. |
31 | */ |
32 | private final double _logBase; |
33 | |
34 | /** |
35 | * Holds the inverse of the natural logarithm of the base. |
36 | */ |
37 | private final double _invLogBase; |
38 | |
39 | /** |
40 | * Holds the inverse of this converter. |
41 | */ |
42 | private final Inverse _inverse = new Inverse(); |
43 | |
44 | /** |
45 | * Creates a logarithmic converter having the specified base. |
46 | * |
47 | * @param base the logarithmic base (e.g. <code>Math.E</code> for |
48 | * the Natural Logarithm). |
49 | */ |
50 | public LogConverter(double base) { |
51 | _base = base; |
52 | _logBase = Math.log(base); |
53 | _invLogBase = 1.0 / _logBase; |
54 | } |
55 | |
56 | /** |
57 | * Returns the logarithmic base of this converter. |
58 | * |
59 | * @return the logarithmic base (e.g. <code>Math.E</code> for |
60 | * the Natural Logarithm). |
61 | */ |
62 | public double getBase() { |
63 | return _base; |
64 | } |
65 | |
66 | @Override |
67 | public UnitConverter inverse() { |
68 | return _inverse; |
69 | } |
70 | |
71 | @Override |
72 | public double convert(double amount) { |
73 | return _invLogBase * Math.log(amount); |
74 | } |
75 | |
76 | @Override |
77 | public boolean isLinear() { |
78 | return false; |
79 | } |
80 | |
81 | /** |
82 | * This inner class represents the inverse of the logarithmic converter |
83 | * (exponentiation converter). |
84 | */ |
85 | private class Inverse extends UnitConverter { |
86 | |
87 | |
88 | @Override |
89 | public UnitConverter inverse() { |
90 | return LogConverter.this; |
91 | } |
92 | |
93 | @Override |
94 | public double convert(double amount) { |
95 | return Math.exp(_logBase * amount); |
96 | } |
97 | |
98 | @Override |
99 | public boolean isLinear() { |
100 | return false; |
101 | } |
102 | |
103 | private static final long serialVersionUID = 1L; |
104 | } |
105 | |
106 | private static final long serialVersionUID = 1L; |
107 | } |