BloodyFoxy

Dichotomy method using BC

Sep 7th, 2014
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.88 KB | None | 0 0
  1. #!/bin/bash
  2. #Dichotomy method
  3. #Equalation acoef*x^2+bcoef*x
  4. acoef="0.5"
  5. bcoef="2"
  6. #[a;b]
  7. a="-2"
  8. b="-3"
  9. #Epsilon, accuracy
  10. e="10^-6"
  11.  
  12. #BC returnes 1 if true and 0 if false
  13. #BC has no ABS function by default
  14. statement=$(echo "define abs(x) {if (x<0) {return -x}; return x;};  abs($b - $a) > $e" | bc)
  15. # [[ works only in bash shell, newer ]]
  16. # [ works in default shell ]
  17. while [[ $statement = 1 ]]
  18. do
  19. #scale makes 6 digits after comma
  20. c=$(echo "scale=6; ($a + $b) / 2" | bc)
  21.         statement=$(echo "scale=6; ($b * $b * $acoef + $b * $bcoef) * ($c * $c * $acoef + $c * $bcoef) < 0" | bc)
  22.         if [[ $statement = 1 ]]
  23.                 then
  24.                         a=$c
  25.                 else
  26.                         b=$c
  27.         fi
  28. statement=$(echo "define abs(x) {if (x<0) {return -x}; return x;};  abs($b - $a) > $e" | bc)
  29. done
  30. echo "scale=6; ($a + $b) / 2" | bc
  31.  
  32. exit 0
Advertisement
Add Comment
Please, Sign In to add comment