0

I want to do math with the pq-formula but for some reason everything works except that the numbers are different then they should be.

The Formula that I want to represent is: x1,2 = -p/2 ± √(p^2/4 -q)

  • If I do the Math with a calculator and not with my program I get other results (I tried with calculator and by hand)

Example with p=12 & q=-12:

what I get: x1 = 9.0 and x2= -21.0 what I want to get (does not have to be exact the same but close): x1 = 0.92820323027551 x2 = -12.928203230276

(teil means part; null means zero)

public class PQ {
  public static void main(String[] args) {
    if (args.length != 2) {
      System.out.println("ERROR: Bitte genau zwei Argumente angeben");
      return;
    }

    double p = Double.parseDouble(args[0]);
    double q = Double.parseDouble(args[1]);
    double teil1 = -(p / 2);
    double teil2 = (Math.sqrt(p * p) / 4 - q);
    double teil3 = (p * p / 4 - q);
    double Null1 = teil1 + teil2;
    double Null2 = teil1 - teil2;

    if (teil3 < 0) {
      System.out.println("Es gibt 0 Nullstellen.");
    }

    if (Null1 > Null2) {
      System.out.println(Null2);
      System.out.println(Null1);
      System.out.println("Es gibt 2 Nullstellen.");
    } else if (Null1 < Null2) {
      System.out.println(Null1);
      System.out.println(Null2);
      System.out.println("Es gibt 2 Nullstellen.");
      return;
    }

    if (Null1 == Null2) {
      System.out.println(Null1);
      System.out.println("Es gibt 1 Nullstelle.");
    }
  }
}

I tried changing the formula but there are always the same results

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
Bennyx
  • 11
  • 3
  • 2
    _"the numbers are different that they should be"_ -- What should they be and what results are you getting? Please read [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) and [Is Floating Point Broken?](https://stackoverflow.com/q/588004/18157) – Jim Garrison Oct 31 '22 at 00:49
  • Maybe you can also add an example with p and q values and what you believe to be the correct output should be. – President James K. Polk Oct 31 '22 at 00:53
  • This looks like an attempt to solve x^2 + p\*x + q = 0. The formula looks correct but your Java does not seem to reflect that formula. Using the quadratic formula one can write the zeros in pseudo-Java as (-p±Math.sqrt(p*p - 4*q)) / 2. – President James K. Polk Oct 31 '22 at 01:04
  • Note that trying to do maths with simple ascii/unicode is not precise enough, so use more syntax to show what the _actual_ formula should be, because the `x1,2` in `x1,2 = -p/2 ± √(p^2/4 -q)` doesn't actually mean anything (it's not maths notation, nor latex notation), and `p^2/4` is `p^0.25` without parentheses. Also, _never_ call your variables `Null`, because `null` is a reserved keyword, there's only one `null`, and variables use lowerCamelCase. – Mike 'Pomax' Kamermans Oct 31 '22 at 01:17

0 Answers0