Calculating degrees to radians in terms of pi

826 Views Asked by At

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"

1

There are 1 best solutions below

0
vityaman On

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)