0

I made a code converting degrees to radians following my teacher's format but I want to try to make it in terms of pi. Right now when I plug in 30 as my degrees the output is a loooong decimal but I want it to come out as pi/6. Is there a way to keep the pi symbol in the output?

This is my current code:

    public static double convertDeg(double deg)
    {
        double rad = deg * (Math.PI/180);
        return rad;
    }

and

System.out.println("Degrees to radians: "+Calculate.convertDeg(30));

The output is: "Degrees to radians: 0.5235987755982988"

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 1
    Why not just leave PI out of the equation completely. Compute `180/deg` and then print "Pi/" followed by the result of your calculation. – CryptoFool Aug 21 '22 at 08:16
  • Or you want `pi / 2` `pi / 3`, `pi / 6` depending on specific results? Like 270 deg -> `3 pi / 2`, 120 deg -> `2 pi / 3` etc? – Federico klez Culloca Aug 21 '22 at 08:18
  • 1
    Your function returns just a number. Per your print statement, you are assuming that your function returns radians. To satisfy those two requirements, you want to do exactly what you're showing above. You can't return a decimal value that includes PI. Why would you want to? If you don't like displaying so many digits, there is an easy way to deal with that in Python. – CryptoFool Aug 21 '22 at 08:24
  • I would like the calculator to be able to simplify the answer, keeping the pi in the numerator (keeping it a fraction instead of a decimal unless that's not a thing) – Username978 Aug 21 '22 at 08:27
  • 2
    It's not a standard thing in Python. It's not a standard thing in programming in general. If you aren't being asked explicitly to do this, I would forget about it. – CryptoFool Aug 21 '22 at 08:30

1 Answers1

0

You can't set formatting up to convert degrees to radians with pi out of the box in java, but you can write your own function to do this.

We know that 
360 degrees = 2 * PI   radians =>
180 degrees = PI       radians =>
1   degree  = PI / 180 radians =>

Therefore
X degrees = PI * (X / 180) radians

In case degrees is an integer value 
  we can simplify a fraction X / 180
  if gcd(X, 180) > 1, gcd -- the greater common divider.
  X / 180 = (X / gcd(X, 180)) / (180 / gcd(X, 180))

The code is something like this (don't forget to check corner cases):

String formatDegreesAsFractionWithPI(int degrees) {
  int gcd = gcd(degrees, 180);
  return "(" + (degrees / gcd) + " / " + (180 / gcd) + ") * PI"
}

int gcd(int a, int b) = { ... }

In case degrees is a floating point number, 
  the problem is more complicated and my advice 
  is to read about 'converting decimal floating 
  point number to integers fraction'.

Related questions: gcd in java, convert float to fraction (maybe works)

vityaman
  • 1
  • 2