Skip to content

Commit

Permalink
Погрешность вычислений (точность вычисления дискриминанта)
Browse files Browse the repository at this point in the history
  • Loading branch information
stden committed May 23, 2015
1 parent 9a243cb commit 14bff05
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/main/java/QuadraticEquation.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* Квадратное уравнение
*/
public class QuadraticEquation {
public static final double EPS = 1e-10;

/**
* Решение квадратного уравнения: ax^2 + bx + c = 0
Expand All @@ -14,7 +15,7 @@ public class QuadraticEquation {
public static double[] solve(double a, double b, double c) {
// Дискриминант
double D = Math.pow(b, 2) - 4 * a * c;
if (D == 0)
if (Math.abs(D) < EPS)
return new double[]{-b / (2 * a)};
double d = Math.sqrt(D);
return new double[]{(-b - d) / (2 * a), (-b + d) / (2 * a)};
Expand Down
11 changes: 11 additions & 0 deletions src/test/java/QuadraticEquationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,15 @@ public void testSimpleOneRoot() {
public void testTwoSolutions() {
assertArrayEquals("(x-1)(x-2) = x^2-3x+2", new double[]{1, 2}, QuadraticEquation.solve(1, -3, 2), EPS);
}

/**
* Погрешность вычислений (точность вычисления дискриминанта)
*/
@Test
public void testOneRootAccuracy() {
for (int q = 1; q < 999; q++) {
double t = 0.3;
assertArrayEquals("t(x-q)^2 = t*x^2 - 2*t*q*x + t*q^2", new double[]{q}, QuadraticEquation.solve(t, -2 * t * q, t * q * q), EPS);
}
}
}

0 comments on commit 14bff05

Please sign in to comment.