Coby Walters
Coby Walters

Reputation: 9

How to go about using tangents in Java?

I was bored and wanted to practice my java coding skills. I made a program that finds the area of a polygon based on what you know (radius, perimeter, apothem).

Here's a portion:

static void pentagon() {
    System.out.println("Select what you know");
    System.out.println("[1]Perimeter\n[2]Apothem\n[3]Radius");
    info = input.nextInt();

    if (info == 1) {
        System.out.println("What is the perimeter of the pentagon?");
        double per = input.nextDouble();
        double apothem = per * .137638192;
        double answer = apothem * per * .5;
        System.out.println("The area of the pentagon is " + answer + " square units.");
    } else if (info == 2) {
        System.out.println("What is the apothem of the pentagon?");
        double apothem = input.nextDouble();
        double per = apothem / .137638192;
        double answer = apothem * per * .5;
        System.out.println("The area of the pentagon is " + answer + " square units.");
    } else if (info == 3) {
        System.out.println("What is the radius of the pentagon?");
        double rad = input.nextDouble();
        double per = rad / .1701301617;
        double apothem = per * .137638192;
        double answer = apothem * per * .5;
        System.out.println("The area of the pentagon is " + answer + " square units.");
    }
}

Due to the problem that all those decimals (ratio of apothem to perimeter) I had to figure out myself, I could only code a few useful ones.

If I knew how to use tangents, I could figure this out.

Ex: double apothem = length / tan(360/10/2)

(An apothem of a decagon) Can someone show me how to code the previous line?

Upvotes: 0

Views: 577

Answers (2)

dkatzel
dkatzel

Reputation: 31648

You're looking for the java.lang.Math class which has all the trig functions along with other useful constants like e and PI

So the apothem of a decagon where each side was length long and the equation = length/ 2 tan(180/ n) would be (after importing the Math class by putting at the top of your java file import java.lang.Math; )

EDIT As user ajb points out, Math.tan() takes radians so you have to convert degrees to radians so you have to use toRadians() to convert from degrees to radians:

 double apothem = length / (2 *Math.tan(Math.toRadians(180/10)) 

Upvotes: 0

redge
redge

Reputation: 1192

The recomended way would be to use java.lang.Math.tan(double a)

double apothem = 1 / java.lang.Math.tan( (2*java.lang.Math.PI)/(10*2))

unless there is some reason why you need extraordinary precision and this does not provide it. Then you may be able to find some third party alternative.

Upvotes: 1

Related Questions