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?
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.
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))
Related
I'm making a trig calculator to practice aviation problems for fun and can't convert radians to degrees properly in java.
I've tried taking altitude divided by Math.tan(angle) and times it by (180 / Math.PI) but this doesn't give me the answer I'm looking for.
The numbers I've tried include alt = 500, angle of approach = 3. My code will store these values and take 500/tan(3) * (180/Pi) and I'm unsure why this isn't the correct trigonometry behind it.
public static void approachPath() {
System.out.println("FINDING THE IDEAL APPROACH PATH . . . ");
System.out.println("What is the altitude of the aircraft:");
double alt = scan.nextDouble();
System.out.println("What is the angle of approach:");
double angleofapproach = scan.nextDouble();
//line my problem occurs on
double approachPath = (alt / Math.tan(angleofapproach)) * (180 / Math.PI);
System.out.println("The ideal approach path is: " + approachPath);
}
I'm expecting the answer 9,541feet so I can move on to writing the rest of the method to find the final approach path in nautical miles.
You were almost right. Just instead of rad to deg, it should be deg to rad.
double angleofapproach = toRad(scan.nextDouble());
double approachPath = (alt / Math.tan(angleofapproach));
// deg to rad
public static double toRad(double deg) {
return deg * (Math.PI / 180);
}
Hi I'm in my first coding class. This is my first code using math and I'm struggling to see where I went wrong, I have no errors but the calculations are undefined.
I need to find the area of the triangle using 3 points. I was given the euqations:
s = (side1 + side2 + side3)/2
area = sqrt(s(s-side)(s- side2)(s-side3))
Side = sqrt(x1-y1)+ (x2-y2)
Please help, here's my code:
double sideOne = Math.sqrt(Math.pow((x1cr - x2cr), 2 + Math.pow((y1cr - y2cr), 2)));
double sideTwo = Math.sqrt(Math.pow((x2cr - x3cr), 2 + Math.pow((y2cr - y3cr), 2)));
double sideThree = Math.sqrt(Math.pow((x1cr - x3cr), 2 + Math.pow((y1cr - y3cr), 2)));
double lSide = (sideOne + sideTwo + sideThree) / 2;
double areaTri = Math.sqrt((lSide * (lSide - sideOne) * (lSide - sideTwo) * (lSide - sideThree)));
System.out.println("The area of your triangle is " + areaTri);
Edit: Here's the example my teacher gave:
Here is a sample run:
Enter the coordinates of the first vertex (x1, y1) of the triangle: 1.5 -3.4
Enter the coordinates of the second vertex (x2, y2) of the triangle: 4.6 5
Enter the coordinates of the third vertex (x3, y3) of the triangle: 9.5 -3.4
The area of the triangle is 33.6 sq cms
The problem is how you're calculating sideOne, sideTwo and sideThree.
I believe you calculate sideOne like this:
Then your code should be:
double sideOne = Math.sqrt(Math.pow((x1cr - x2cr), 2) + Math.pow((y1cr - y2cr), 2));
^ ^
1 2
Note that the formula is same, but the placement of bracket is different. A bracket from position 2 is shifted to position 1.
Similar changes should be done while calculating sideTwo and sideThree as well.
Please review the code and the comments. Don't hesitate to ask if it is not clear:
class Test {
//always post MCVE (stackoverflow.com/help/mcve)
public static void main(String[] args) {
double x1cr=1.5, y1cr=-3.4, //side one end points
x2cr=4.6, y2cr=5, //side two end points
x3cr=9.5, y3cr=-3.4; //side three end points
double sideOne = Math.sqrt(squareIt(x1cr, x2cr)+ squareIt(y1cr, y2cr) );
double sideTwo = Math.sqrt(squareIt(x2cr, x3cr) + squareIt(y2cr, y3cr));
double sideThree = Math.sqrt(squareIt(x1cr, x3cr)+ squareIt(y1cr, y3cr));
System.out.println(sideOne+ " "+ sideTwo+ " "+ sideThree);
double lSide = (sideOne + sideTwo + sideThree) / 2;
double areaTri = Math.sqrt((lSide * (lSide - sideOne) * (lSide - sideTwo) * (lSide - sideThree)));
System.out.println("The area of your triangle is " + areaTri);
}
//put the repeating calculation in a function
//it is easy to check such function by say :
// System.out.println(squareIt(5., 3.));
static double squareIt(Double x1, double x2) {
return Math.pow((x1 - x2), 2);
}
}
So i'm trying to make a simple calculator to calculate a wilks score. I'm not getting the correct answer which i'm sure is because i'm not setting up the formula correctly. If I pass in a weight of 180, squat of 300, bench of 300, and deadlift of 400 in lbs I should be getting a wilks of 305.78 but i'm getting 2.0414858^-5
Heres my calcWilks method
public double calcWilks(double weight, double squat, double bench, double deadLift) {
double a = -216.0475144;
double b = 16.2606339;
double c = -0.002388645;
double d = -0.00113732;
double e = Math.pow(7.01863, -6);
double f = Math.pow(-1.291, -8);
double x = weight;
double coeff;
double score;
coeff = 500 / (a + (b*x) + (c* Math.pow(x, 2))+ (d* Math.pow(x, 3))
+ (e* Math.pow(x, 4)) + (f* Math.pow(x, 5)));
double total = squat + bench + deadLift;
score = coeff* total;
return score;
}
and heres a link to the actual formaula https://en.wikipedia.org/wiki/Wilks_Coefficient
I'm trying to use the Male formula
Thanks for any help!
The e coefficient's value in the wikipedia page is
7.01863E-06
but you've used
Math.pow(7.01863, -6)
That's not the same thing:
7.01863E-06 = 7.01863 * Math.pow(10, -6).
Just use the value 7.01863E-06 (or 7.01863e-6) directly.
(Same problem with f)
Also, note that the inputs to the formula should be in kilograms; not in pounds, as you state in the question.
Sorry to trouble but it seems I'm a little lost.
I am currently creating a Shape Calculator for 2D and 3D shapes and I seem to be having a problem with the above mentioned shapes in the title.
Now I have gone about trying to use this particular section of code to get the Area of my Pentagon, I've seen this work elsewhere but can't figure out why it won't work here even after reviewing and comparing my code? I thought someone could possibly point out if this is the correct way to go about solving it or if I've made a mistake I can't see myself? Generally need a second opinion sorry.
double pen = scan.nextDouble();
double penPerm = pen * 5;
double A1 = pen * Math.sqrt(5);
double A2 = 5 + A1;
double A3 = Math.sqrt(5 * A2);
double PenA = (1.0 / 4.0) * A3 * Math.pow(pen, 2);
System.out.println("Your Perimitre is :" + penPerm + "cm and your Area is :" + PenA + "cm Squared");
The other problem I have how should I go about tackling the Hexagon but to be honest, the above Pentagon problem is my main concern before I move onto the Hexagon.
For a regular pentagon you can try the following code:
public static void main(String[] args) {
double side = 10;
double area = (1.0/4.0) * Math.sqrt(5*(5+2*Math.sqrt(5))) * Math.pow(side,2);
System.out.println("Your Perimitre is :" + 5*side + "cm and your Area is :" + area + "cm Squared");
}
You can also try the following code which takes no of sides (n) and edge size (s) as input and computes area for a regular polygon:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Enter the number of sides in polygon");
int n = input.nextInt();
System.out.println(" Enter the distance between two points");
double s = input.nextDouble();
double area = (n * Math.pow(s, 2)) / (4 * Math.tan(Math.PI / n));
//Print result
System.out.println (" Area is " + area);
System.out.println (" Perimeter is " + s*n);
}
I know how to start it out and I know how to put in the scanners and everything, but in school, I've never really learned about longitude and latitude formulas and how to convert those points into radians. So I'm pretty much stuck on this Java problem. Here is what I have so far:
import java.util.*;
class DistanceCalculator {
// Radius of the earth in km; this is the class constant.
public static final double Radius = 6372.795;
/**
* This program computes the spherical distance between two points on the surface of the Earth.
*/
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
intro();
System.out.print("Longitude (degrees.minutes) ");
double Longitude = console.nextDouble();
System.out.print("Latitude (degrees.minutes) ");
double Latitude = console.nextDouble();
}
public static double distFrom(double lat1, double lng1, double lat2, double lng2);
double Latitude = Math.toRadians(...);
}
public static void intro() {
System.out.println("This program computes the spherical distance between two points on the surface of the Earth.");
System.out.println("\tPlease start by entering the longitude and the latitude of location 1.");
}
}
In Java IDE, they say that Longitude and Latitude points (the ones underneath the intro();) are not used, and I know why, since I haven't really defined them yet.
I know I'm missing the formula for longitude and latitude. In my book, it wants me to use the spherical law of cosines, and since I've never learned this at school, no matter how hard I study the formula from the websites I sought out, I don't know how to transfer that into Java language.
Another problem is, how do I transfer degrees and minutes from a longitude/latitude point into radians? Do I have to use Math.toRadians thing? Oh yeah and also, my answer has to be in kilometers.
Updated: The math functions some of you guys are talking about confuses me greatly. In school (I'm a high schooler), even at Math IB SL, my teacher has never taught us how to find long/lat. points...yet. So it's hard for me to grasp. Since the spherical law of cosines formula is online, do I basically just take that formula and convert it into "java language" and plug it into my program?
The key word you need to search for is the "Haversine formula".
An easier to understand method, but one which is not quite so accurate for small distances, is to recall that the angle between two vectors A and B can be calculated using the dot product:
A ⋅ B = |A| * |B| * cos(theta)
so if you convert your polar lat/long pairs into 3D cartesian coordinates (and yes, you'll need to use Math.toRadians(), Math.cos() and Math.sin() to do that, and then calculate the dot product, you'll then get cos(theta), so use Math.acos() to get theta.
You can then work out the distance simply as D = R * theta, where R is the radius of the Earth, and theta remains in radians.
I suggest to read more about WGS84.
Mathematical explanations here.
You may look at this link for the logic.
http://aravindtrue.wordpress.com/2009/06/30/calculate-distance-using-latitude-and-longitude-php-mysql/
Function in PHP... I don't know Java. So some one edit my post. Here is the PHP function:
function getDistanceBetweenPointsNew($latitude1, $longitude1,
$latitude2, $longitude2, $unit = 'Mi')
{
$theta = $longitude1 - $longitude2;
$distance = (sin(deg2rad($latitude1)) *
sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) *
cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
$distance = acos($distance);
$distance = rad2deg($distance);
$distance = $distance * 60 * 1.1515;
switch($unit)
{
case 'Mi': break;
case 'Km' : $distance = $distance *1.609344;
}
return (round($distance,2));
}
also to get value from MySQL database:
Calculate distance given 2 points, latitude and longitude
I tried to create a java function, I don't know if it work or not.
try this. If any one can help, try edit my java code.
import java.math.BigDecimal;
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
public static double distFrom(double lat1, double lng1, double lat2, double lng2, String unit)
{
double theta = lng1 - lng2;
double distance = (
Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
)+(
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta))
);
distance = Math.acos(distance);
distance = Math.toDeg(distance);
distance = distance * 60 * 1.1515;
switch(unit)
{
/* Mi = miles, Km = Kilometers */
case "Mi" :
break;
case "Km" :
distance = distance *1.609344;
break;
}
distance = round(distance, 2, BigDecimal.ROUND_HALF_UP);
return distance;
}
import java.util.*;
public class SphericalDistance {
public static void main(String[] args){
System.out.println(" This program computes the spherical distance\n between two points, 1 and 2.");
System.out.println(" Please enter the latitude and longitude for \n each point as a pair of integers, degrees \n followed by minutes:");
System.out.print("Latitude 1:");
Scanner s=new Scanner(System.in);
double latangledeg = s.nextDouble();
double latanglemin = s.nextDouble()/60;
double phideg = latangledeg + latanglemin;
double phi1 = phideg * Math.PI/180;
System.out.print("Longitude 1:");
double lonangledeg = s.nextDouble();
double lonanglemin = s.nextDouble()/60;
double lambdadeg = lonangledeg + lonanglemin;
double lambda1 = lambdadeg * Math.PI/180;
System.out.println("Latitude 2:");
double latangledeg2 = s.nextDouble();
double latanglemin2 = s.nextDouble()/60;
double phideg2 = latangledeg2 + latanglemin2;
double phi2 = phideg2 * Math.PI/180;
System.out.println("Longitude 2:");
double lonangledeg2 = s.nextDouble();
double lonanglemin2 = s.nextDouble()/60;
double lambdadeg2 = lonangledeg2 + lonanglemin2;
double lambda2 = lambdadeg2 * Math.PI/180;
double lambdaf = lambda2 - lambda1;
double angdistance = Math.acos(Math.sin(phi1)*Math.sin(phi2) + Math.cos(phi1)*Math.cos(phi2)*Math.cos(lambdaf));
System.out.println("Angular Distance = " + angdistance + " radians");
int distancekm = (int)(angdistance * 6372.795);
int distancemi = (int) (distancekm * .621371);
System.out.println("Distance = " + distancekm + " kilometers");
System.out.println("Distance = " + distancemi + " miles");
s.close();
}
}