Advertisement
Guest User

Bisekcja

a guest
Oct 24th, 2017
632
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. import java.lang.Math.*;
  2.  
  3. class liniowa implements Function{
  4. public double getValue(double x){
  5. return x-5;
  6.     }
  7. }
  8.  
  9. class kwadratowa implements Function{
  10. public double getValue(double x){
  11. return x*2*x+x-8;
  12.     }
  13. }
  14.  
  15. class wielomianowa implements Function{
  16. public double getValue(double x)
  17. {
  18. return 4*x*x*x*x+3*x*x*x+2*x*x-3*x+8;
  19. }
  20. }
  21.  
  22. class bisekcja{
  23.  
  24. static double E = 0.00000001;
  25.  
  26. public static double oblicz(double a, double b, Function f){
  27.  
  28. double x0;
  29.  
  30. while(Math.abs(a - b) > E)
  31. {
  32. x0 = (a + b) / 2;
  33. if(f.getValue(x0) == 0)
  34. break;
  35. else if((f.getValue(a) * f.getValue(x0) < 0) && (f.getValue(x0) * f.getValue(b) > 0))
  36.     b = x0;
  37. else if((f.getValue(x0) * f.getValue(a) > 0) && (f.getValue(x0) * f.getValue(b)) < 0)
  38.     a =x0;
  39. else
  40. break;
  41.  
  42. }
  43. return (a + b) / 2;
  44. }
  45.  
  46. public static void main(String[] args){
  47.  
  48.     double x;
  49.     double a = Double.parseDouble(args[1]);
  50.     double b = Double.parseDouble(args[2]);
  51.    
  52.     if(args[0].equals("liniowa"))
  53.     {
  54.     Function f = new liniowa();
  55.     x = oblicz(a, b, f);
  56.     System.out.println("Pierwiastek z funkcji: " + args[0].toString() + " wynosi: " + x);
  57.     }
  58.     else if(args[0].equals("kwadratowa"))
  59.     {
  60.     Function f = new kwadratowa();
  61.     x = oblicz(a, b, f);
  62.     System.out.println("Pierwiastek z funkcji: " + args[0].toString() + " wynosi: " + x);
  63.     }
  64.     else if(args[0].equals("wielomianowa"))
  65.     {
  66.     Function f = new wielomianowa();
  67.     x = oblicz(a, b, f);
  68.     System.out.println("Pierwiastek z funkcji: " + args[0].toString() + " wynosi: " + x);
  69.     }
  70.     else
  71.     System.out.println("Brak/bledne argumenty");
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement