Приветствую !
Вот такой код на Delphi7 ( вычисление корней квадратного уравнения )
| Код | function Quadratic(const a:double; const b:double; const c:double; var x0, x1: double):integer; var t, d: double; px0:PDouble; x2:PDouble; begin (* degenerated cases *) if a = 0. then begin if b = 0. then begin if c = 0. then begin Result := -3; Exit; end; Result := -2; Exit; end; x0 := -c / b; Result := -1; Exit; end; (* the main case *) d := b * b - 4. * a * c; // the discriminant ///* one distinct root */ if d = 0. then begin x1 := -b / (2. * a); x0 := x1; Result := 1; Exit; end; (* * conjugate complex roots - if u need it. Otherwise change this part *) if d < 0. then begin t := 0.5 / a; x0 := -b * t; x1 := sqrt(-d) * t; Result := 0; Exit; end; ///* 2 real roots: avoid subtraction of 2 close numbers */ if b >= 0. then begin d := (-0.5) * (b + sqrt(d)); end else begin d := (-0.5) * (b - sqrt(d)); end; x0 := d / a; x1 := c / d; Result := 2; Exit; end;
procedure TForm3.Button7Click(Sender: TObject); var i, j: integer; //x:array[0..1] of double; x0, x1: double; start: dword; begin start := GetTickCount(); for i := 0 to 2000000 do begin Quadratic(1, 4, 3, x0, x1); end; ShowMessage(IntToStr(GetTickCount - start));
end;
|
исполняется 250 ms
Вот такой код на Java 1.5 ( Windows XP )
| Код | /* * Quadratic equation solution. Real coefficients case. * * int Quadratic(double *x,double a,double b,double c); Parameters: x - * solution array (size 2). On output: 2 real roots -> then x is filled with * them; 2 complex-conjugate roots -> x[0] is real part, x[1] is * non-negative imaginary part. other cases -> x[0] unique valid root if * (-1) returned, no valid roots otherwise. a, b, c - coefficients: ax^2 + * bx + c = 0. Returns: 2 - 2 real and distince roots; 1 - 1 real distinct * root (x[0]=x[1]); 0 - 2 complex roots; -1 - one real root in case a==0; * -2 - no roots in case a=0, b=0; -3 - infinite number of roots (a=b=c=0). */
int Quadratic(double x[], double a, double b, double c) { double d; /* degenerated cases */ if (a == 0.) { if (b == 0.) { if (c == 0.) return (-3); return (-2); } x[0] = -c / b; return (-1); } /* the main case */ d = b * b - 4. * a * c; /* the discriminant */ /* one distinct root */ if (d == 0.) { x[0] = x[1] = -b / (2. * a); return (1); } /* * conjugate complex roots - if u need it. Otherwise change this part */ if (d < 0.) { double t = 0.5 / a; x[0] = -b * t; x[1] = Math.sqrt(-d) * t; return (0); } /* 2 real roots: avoid subtraction of 2 close numbers */ if (b >= 0.) d = (-0.5) * (b + Math.sqrt(d)); else d = (-0.5) * (b - Math.sqrt(d)); x[0] = d / a; x[1] = c / d; return (2); }
public void testSpeed() { double x[] = new double[2];
long start = System.currentTimeMillis(); for (int i = 0; i < 2000000; i++) { Quadratic(x, 1, 4, 3); } trace(System.currentTimeMillis() - start);
}
|
исполняется 150 ms
Т.е. Java работает почти в два раза быстрее.
Комментарии ? |