PageRenderTime 14ms CodeModel.GetById 7ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/Task/Numeric-error-propagation/Java/numeric-error-propagation.java

https://github.com/acmeism/RosettaCodeData
Java | 87 lines | 71 code | 16 blank | 0 comment | 0 complexity | a668320673e8fe551a9a827dc4eddb21 MD5 | raw file
 1public class Approx {
 2    private double value;
 3    private double error;
 4
 5    public Approx(){this.value = this.error = 0;}
 6
 7    public Approx(Approx b){
 8        this.value = b.value;
 9        this.error = b.error;
10    }
11
12    public Approx(double value, double error){
13        this.value = value;
14        this.error = error;
15    }
16
17    public Approx add(Approx b){
18        value+= b.value;
19        error = Math.sqrt(error * error + b.error * b.error);
20        return this;
21    }
22
23    public Approx add(double b){
24        value+= b;
25        return this;
26    }
27
28    public Approx sub(Approx b){
29        value-= b.value;
30        error = Math.sqrt(error * error + b.error * b.error);
31        return this;
32    }
33
34    public Approx sub(double b){
35        value-= b;
36        return this;
37    }
38
39    public Approx mult(Approx b){
40        double oldVal = value;
41        value*= b.value;
42        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
43                                  (b.error*b.error) / (b.value*b.value));
44        return this;
45    }
46
47    public Approx mult(double b){
48        value*= b;
49        error = Math.abs(b * error);
50        return this;
51    }
52
53    public Approx div(Approx b){
54        double oldVal = value;
55        value/= b.value;
56        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
57                                  (b.error*b.error) / (b.value*b.value));
58        return this;
59    }
60
61    public Approx div(double b){
62        value/= b;
63        error = Math.abs(b * error);
64        return this;
65    }
66
67    public Approx pow(double b){
68        double oldVal = value;
69        value = Math.pow(value, b);
70        error = Math.abs(value * b * (error / oldVal));
71        return this;
72    }
73
74    @Override
75    public String toString(){return value+"Âą"+error;}
76
77    public static void main(String[] args){
78        Approx x1 = new Approx(100, 1.1);
79        Approx x2 = new Approx(50, 1.2);
80        Approx y1 = new Approx(200, 2.2);
81        Approx y2 = new Approx(100, 2.3);
82
83        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);
84
85        System.out.println(x1);
86    }
87}