probability.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-1.6.0).
03  * Copyright (c) 2007-2014 Franz Wilhelmstötter
04  *
05  * Licensed under the Apache License, Version 2.0 (the "License");
06  * you may not use this file except in compliance with the License.
07  * You may obtain a copy of the License at
08  *
09  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * Author:
18  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
19  */
20 package org.jenetics.internal.math;
21 
22 import static org.jenetics.util.math.pow;
23 
24 import org.jenetics.util.StaticObject;
25 
26 /**
27  * Mathematical functions regarding probabilities.
28  *
29  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
30  @since 1.4
31  @version 1.4 &mdash; <em>$Date: 2013-09-01 $</em>
32  */
33 public final class probability extends StaticObject {
34     private probability() {}
35 
36     private static final long INT_RANGE = pow(2321;
37 
38     /**
39      * Maps the probability, given in the range {@code [0, 1]}, to an
40      * integer in the range {@code [Integer.MIN_VALUE, Integer.MAX_VALUE]}.
41      *
42      @see {@link #toInt(double)}
43      @see {@link #toFloat(int)}
44      *
45      @param probability the probability to widen.
46      @return the widened probability.
47      */
48     public static int toInt(final float probability) {
49         return Math.round(INT_RANGE*probability + Integer.MIN_VALUE);
50     }
51 
52     /**
53      * Maps the probability, given in the range {@code [0, 1]}, to an
54      * integer in the range {@code [Integer.MIN_VALUE, Integer.MAX_VALUE]}.
55      *
56      @see {@link #toInt(float)}
57      @see {@link #toFloat(int)}
58      *
59      @param probability the probability to widen.
60      @return the widened probability.
61      */
62     public static int toInt(final double probability) {
63         return (int)(Math.round(INT_RANGE*probability+ Integer.MIN_VALUE);
64     }
65 
66     /**
67      * Maps the <i>integer</i> probability, within the range
68      * {@code [Integer.MIN_VALUE, Integer.MAX_VALUE]} back to a float
69      * probability within the range {@code [0, 1]}.
70      *
71      @see {@link #toInt(float)}
72      @see {@link #toInt(double)}
73      *
74      @param probability the <i>integer</i> probability to map.
75      @return the mapped probability within the range {@code [0, 1]}.
76      */
77     public static float toFloat(final int probability) {
78         final long value = (long)probability + Integer.MAX_VALUE;
79         return (float)(value/(double)INT_RANGE);
80     }
81 }