summaryrefslogtreecommitdiffstats
path: root/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/TruthOperator.java
blob: fc2598679230f2cb34244669d33d1509cc8240e4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchlib.rankingexpression.rule;

import java.io.Serializable;

/**
 * A mathematical operator
 *
 * @author bratseth
 */
public enum TruthOperator  implements Serializable {

    SMALLER("<")   { public boolean evaluate(double x, double y) { return x<y; } },
    SMALLEREQUAL("<=")  { public boolean evaluate(double x, double y) { return x<=y; } },
    EQUAL("==")  { public boolean evaluate(double x, double y) { return x==y; } },
    APPROX_EQUAL("~=") { public boolean evaluate(double x, double y) { return approxEqual(x,y); } },
    LARGER(">")   { public boolean evaluate(double x, double y) { return x>y; } },
    LARGEREQUAL(">=")  { public boolean evaluate(double x, double y) { return x>=y; } },
    NOTEQUAL("!=")  { public boolean evaluate(double x, double y) { return x!=y; } };

    private final String operatorString;

    TruthOperator(String operatorString) {
        this.operatorString = operatorString;
    }

    /** Perform the truth operation on the input */
    public abstract boolean evaluate(double x, double y);

    @Override
    public String toString() { return operatorString; }

    public static TruthOperator fromString(String string) {
        for (TruthOperator operator : values())
            if (operator.toString().equals(string))
                return operator;
        throw new IllegalArgumentException("Illegal truth operator '" + string + "'");
    }

    private static boolean approxEqual(double x,double y) {
        if (y < -1.0 || y > 1.0) {
            x = Math.nextAfter(x/y, 1.0);
            y = 1.0;
        } else {
            x = Math.nextAfter(x, y);
        }
        return x==y;
    }

}