PageRenderTime 145ms CodeModel.GetById 12ms RepoModel.GetById 0ms 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
  1. public class Approx {
  2. private double value;
  3. private double error;
  4. public Approx(){this.value = this.error = 0;}
  5. public Approx(Approx b){
  6. this.value = b.value;
  7. this.error = b.error;
  8. }
  9. public Approx(double value, double error){
  10. this.value = value;
  11. this.error = error;
  12. }
  13. public Approx add(Approx b){
  14. value+= b.value;
  15. error = Math.sqrt(error * error + b.error * b.error);
  16. return this;
  17. }
  18. public Approx add(double b){
  19. value+= b;
  20. return this;
  21. }
  22. public Approx sub(Approx b){
  23. value-= b.value;
  24. error = Math.sqrt(error * error + b.error * b.error);
  25. return this;
  26. }
  27. public Approx sub(double b){
  28. value-= b;
  29. return this;
  30. }
  31. public Approx mult(Approx b){
  32. double oldVal = value;
  33. value*= b.value;
  34. error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
  35. (b.error*b.error) / (b.value*b.value));
  36. return this;
  37. }
  38. public Approx mult(double b){
  39. value*= b;
  40. error = Math.abs(b * error);
  41. return this;
  42. }
  43. public Approx div(Approx b){
  44. double oldVal = value;
  45. value/= b.value;
  46. error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
  47. (b.error*b.error) / (b.value*b.value));
  48. return this;
  49. }
  50. public Approx div(double b){
  51. value/= b;
  52. error = Math.abs(b * error);
  53. return this;
  54. }
  55. public Approx pow(double b){
  56. double oldVal = value;
  57. value = Math.pow(value, b);
  58. error = Math.abs(value * b * (error / oldVal));
  59. return this;
  60. }
  61. @Override
  62. public String toString(){return value+"Âą"+error;}
  63. public static void main(String[] args){
  64. Approx x1 = new Approx(100, 1.1);
  65. Approx x2 = new Approx(50, 1.2);
  66. Approx y1 = new Approx(200, 2.2);
  67. Approx y2 = new Approx(100, 2.3);
  68. x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);
  69. System.out.println(x1);
  70. }
  71. }