-1

Is there a Java operator that would create a value equal to count but in fewer lines?

    double theta = //Some value;
    int count = 0;
    while (theta > 0) {
        theta -= pi * (1.0 / 8.0);
        count += 1;
    }
J.Doe
  • 1,502
  • 13
  • 47

3 Answers3

2

You've just implemented division by repeated subtraction.

So, if you had actual real numbers in Java, you could do ...

int result = (int) (theta / (Math.PI / 8)) + 1;

... to get the same result. However due to repeated rounding errors in your code, that has many more steps than a simple division, the answers will diverge a bit. The results will be the same for thetas up to around 55 million.

The rounding errors are there because float and double are not accurate representations of real numbers.

See also: Is floating point math broken?

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
1

Assuming theta > 0, something like this should work:

int count = (int)Math.ceil (theta/(Math.PI * (1.0 / 8.0)));

or

int count = (int)Math.ceil (theta*8/Math.PI);
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    The code posted by the OP does neither exactly `Math.ceil` nor `+ 1`, there are edge cases for both (take theta is `Math.PI / 8` or `Math.PI * 8`) – Erwin Bolwidt Feb 27 '18 at 07:03
0

How about this: Math.ceil( theta/(pi * (1.0 / 8.0)))?

Egan Wolf
  • 3,533
  • 1
  • 14
  • 29