Home > Software design >  Calculating degrees to radians in terms of pi
Calculating degrees to radians in terms of pi

Time:08-22

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"

CodePudding user response:

"but I want it to come out as pi/6." To get this format; Try this.

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

It returns a string as the method return type is string. It does'nt exactly return "pi/6" but "Math.PI/6". So get the idea for its use from this;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

class HelloWorld {
    
     public static String convertDeg(double deg)
{
    String rad = "Math.PI/" (180/deg); 
    return rad;
}

    public static void main(String[] args) {
         ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
          try {
         Object result = engine.eval(convertDeg(30));
 
            System.out.println("\nDegree to Radian = " result);
          }
            catch (ScriptException e) {
            // Something went wrong
            e.printStackTrace();
        }
    }
}

Its answer is as follows,

Degree to Radian = 0.5235987755982988

CodePudding user response:

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)

  • Related