Having trouble with my math? Very simple java - java

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);
}
}

Related

Defining height of triangle in coordinate system

I'm writing exercise program with user input of three points in coordinate system, so it get's you length of all sides of given triangle, so as perimeter and area. My goal is to define height of given triangle, so that i can tell if input points equals to straight line in coo-system, triangle doesnt exist, becouse height=0, also to define area of triangle.So how can i define height by given only A, B and C? Any suggestions for typing my code to look better is always welcome! :)
So, my code looks like this:
import java.text.DecimalFormat;
import java.util.Scanner;
public class MainTriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double aX;
double aY;
double bX;
double bY;
double cX;
double cY;
System.out.println("-Distance between 3 points in coordinate system-");
System.out.println();
System.out.print("point A(x):");
aX = sc.nextDouble();
System.out.print("point A(y):");
aY = sc.nextDouble();
System.out.print("point B(x):");
bX = sc.nextDouble();
System.out.print("point B(y):");
bY = sc.nextDouble();
System.out.print("point C(x):");
cX = sc.nextDouble();
System.out.print("point C(y):");
cY = sc.nextDouble();
System.out.println();
sc.close();
double dX = bX - aX;
double dY = bY - aY;
double eX = cX - bX;
double eY = cY - bY;
double fX = cX - aX;
double fY = cY - aY;
double sD = Math.pow(dX, 2) + Math.pow(dY, 2);
double d = Math.sqrt(sD); // length of d (from point A to point B)
double sE = Math.pow(eX, 2) + Math.pow(eY, 2);
double e = Math.sqrt(sE); // length of e (from point B to point C)
double sF = Math.pow(fX, 2) + Math.pow(fY, 2);
double f = Math.sqrt(sF); // length of f (from point C to point A)
System.out.println("Distance from point A to point B is "+new DecimalFormat("##.##").format(d));
System.out.println();
System.out.println("Distance from point B to point C is "+new DecimalFormat("##.##").format(e));
System.out.println();
System.out.println("Distance from point C to point A is "+new DecimalFormat("##.##").format(f));
System.out.println();
double p = d+e+f; // (perameter)
System.out.println("Perameter of triangle ABC is "+new DecimalFormat("##.##").format(p));
}
}
double p = d + e + f;
double area = Math.sqrt( p * (p-d) * (p-e) * (p-f) );
double heightD = (2 * area) / d; //height of edge d
according to question; d, e and f are edges of the triangle. you can calculate area by knowing an edge and height of that edge or by knowing 3 edges lenghts. If you know all edges lenghts, you can get height of an edge
You want to find height of the triangle based on the given points, right? Every triangle has three heights, so you can calculate them using Heron's formula.
For any triangle with sides a, b, c and semiperimeter s = (a + b + c) / 2 the altitude from side a is given by: ha = (2*sqrt(s*(s-a)*(s-b)*(s-c)))/a
Note that a,b,c here are the lengths of the sides of the triangle.
Then you can check if any of the heights are zero.
The height of a 'real' triangle depends on which side is on the floor. But you are looking for a non-triangle. i.e. a non-triangle who's three points lie on a straight line.
To work this out you can simply work out the gradient of two of the 'sides'. If they are the same then you know you have a 'non-triangle'
gradient1 = (y2 -y1)/(x2 - x1)
gradient2 = (y3 -y1)/(x3 - x1)
If gradient1 == gradient2 then you have a 'non-triangle'. As double type arithmetic can lead to slight difference you might want to be able to tolerate minor difference in gradient (e.g. if the difference is < 0.0001 then it's a non-triangle)
Update: Probably also need to cater for divide by zero error too!
The height of the triangle is existent between three units.
The A) Base-A
The B) Base-B
The H) Height-C
A^2 + B^2 = C^2

Shape Calculator Pentagon and Hexagon Perimeter and Area

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);
}

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?
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))

How to get the size of the intersecting part in a circle in Java

I need the size of the black part of this image:
I've done some research about how to find it in normal math, and I was pointed to this website: Website
The final answer on getting it was
(from MathWorld - A Wolfram Web Resource: wolfram.com)
where r is the radius of the first circle, R the radius of the second circle, and d the distance between the two centers.
The code I tried to use to get the size of this was the following:
float r = getRadius1();
float R = e.getRadius1();
float deltaX = Math.abs((getX() + getRadius()) - (e.getX() + e.getRadius()));
float deltaY = Math.abs((getY() + getRadius()) - (e.getY() + e.getRadius()));
float d = (float) Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
float part, part2, part3;
//Chopping it in parts, because it's easier.
part = (float) (Math.pow(r,2) * Math.acos(
Math.toRadians((Math.pow(d, 2) + Math.pow(r, 2) - Math.pow(R, 2))/(2*d*r))));
part2 = (float) (Math.pow(R,2) * Math.acos(
Math.toRadians((Math.pow(d, 2) + Math.pow(R, 2) - Math.pow(r, 2))/(2*d*R))));
part3 = (float) (0.5 * Math.sqrt((-d + r + R) * (d+r-R) * (d-r+R) * (d+r+R)));
float res = part + part2 - part3;
Main.log(res + " " + part + " " + part2 + " " + part3+ " "
+ r + " " + R + " " + d);
//logs the data and System.out's it
I did some testing, and the output was this:
1345.9663 621.6233 971.1231 246.78008 20.0 25.0 43.528286
So that indicates that the size of the overlapping part was bigger than the circle itself (which is r^2 * PI).
What did I do wrong?
Just a guess (as stated in my comment): try removing the Math.toRadians(...) conversion.
Since there are no degrees involved in the formula but rather radii, I assume the parameter to cos-1(...) is already a value in radians.
If I remove the conversion and run your code, I get the following overlap area size: 11.163887023925781 which seems plausible since the length of the overlap segment on the line between the two centers is 20 + 25 - 43.5 = 1.5 (approximated)
Edit:
If I set the distance to 5 (the smaller circle is completely contained in the bigger one but touches its edge) I get the overlap area size 1256.63 which is exactly the area of the smaller circle (202 * Π). The calculation doesn't seem to work if the distance is smaller than the difference of the radii (i.e. in your case smaller than 5), but that might just be a problem of numerical representation (the normal datatypes might not be able to represent some of the intermediate results).

Calculating the angle between two lines without having to calculate the slope? (Java)

I have two Lines: L1 and L2. I want to calculate the angle between the two lines. L1 has points: {(x1, y1), (x2, y2)} and L2 has points: {(x3, y3), (x4, y4)}.
How can I calculate the angle formed between these two lines, without having to calculate the slopes? The problem I am currently having is that sometimes I have horizontal lines (lines along the x-axis) and the following formula fails (divide by zero exception):
arctan((m1 - m2) / (1 - (m1 * m2)))
where m1 and m2 are the slopes of line 1 and line 2 respectively. Is there a formula/algorithm that can calculate the angles between the two lines without ever getting divide-by-zero exceptions? Any help would be highly appreciated.
This is my code snippet:
// Calculates the angle formed between two lines
public static double angleBetween2Lines(Line2D line1, Line2D line2)
{
double slope1 = line1.getY1() - line1.getY2() / line1.getX1() - line1.getX2();
double slope2 = line2.getY1() - line2.getY2() / line2.getX1() - line2.getX2();
double angle = Math.atan((slope1 - slope2) / (1 - (slope1 * slope2)));
return angle;
}
Thanks.
The atan2 function eases the pain of dealing with atan.
It is declared as double atan2(double y, double x) and converts rectangular coordinates (x,y) to the angle theta from the polar coordinates (r,theta)
So I'd rewrite your code as
public static double angleBetween2Lines(Line2D line1, Line2D line2)
{
double angle1 = Math.atan2(line1.getY1() - line1.getY2(),
line1.getX1() - line1.getX2());
double angle2 = Math.atan2(line2.getY1() - line2.getY2(),
line2.getX1() - line2.getX2());
return angle1-angle2;
}
Dot product is probably more useful in this case. Here you can find a geometry package for Java which provides some useful helpers. Below is their calculation for determining the angle between two 3-d points. Hopefully it will get you started:
public static double computeAngle (double[] p0, double[] p1, double[] p2)
{
double[] v0 = Geometry.createVector (p0, p1);
double[] v1 = Geometry.createVector (p0, p2);
double dotProduct = Geometry.computeDotProduct (v0, v1);
double length1 = Geometry.length (v0);
double length2 = Geometry.length (v1);
double denominator = length1 * length2;
double product = denominator != 0.0 ? dotProduct / denominator : 0.0;
double angle = Math.acos (product);
return angle;
}
Good luck!
dx1 = x2-x1;
dy1 = y2-y1;
dx2 = x4-x3;
dy2 = y4-y3;
d = dx1*dx2 + dy1*dy2; // dot product of the 2 vectors
l2 = (dx1*dx1+dy1*dy1)*(dx2*dx2+dy2*dy2) // product of the squared lengths
angle = acos(d/sqrt(l2));
The dot product of 2 vectors is equal to the cosine of the angle time the length of both vectors. This computes the dot product, divides by the length of the vectors and uses the inverse cosine function to recover the angle.
Maybe my approach for Android coordinates system will be useful for someone (used Android PointF class to store points)
/**
* Calculate angle between two lines with two given points
*
* #param A1 First point first line
* #param A2 Second point first line
* #param B1 First point second line
* #param B2 Second point second line
* #return Angle between two lines in degrees
*/
public static float angleBetween2Lines(PointF A1, PointF A2, PointF B1, PointF B2) {
float angle1 = (float) Math.atan2(A2.y - A1.y, A1.x - A2.x);
float angle2 = (float) Math.atan2(B2.y - B1.y, B1.x - B2.x);
float calculatedAngle = (float) Math.toDegrees(angle1 - angle2);
if (calculatedAngle < 0) calculatedAngle += 360;
return calculatedAngle;
}
It return positive value in degrees for any quadrant: 0 <= x < 360
You can checkout my utility class here
The formula for getting the angle is tan a = (slope1-slope2)/(1+slope1*slope2)
You are using:
tan a = (slope1 - slope2) / (1 - slope1 * slope2)
So it should be:
double angle = Math.atan((slope1 - slope2) / (1 + slope1 * slope2));
First, are you sure the brackets are in the right order? I think (could be wrong) it should be this:
double slope1 = (line1.getY1() - line1.getY2()) / (line1.getX1() - line1.getX2());
double slope2 = (line2.getY1() - line2.getY2()) / (line2.getX1() - line2.getX2());
Second, there are two things you could do for the div by zero: you could catch the exception and handle it
double angle;
try
{
angle = Math.atan((slope1 - slope2) / (1 - (slope1 * slope2)));
catch (DivideByZeroException dbze)
{
//Do something about it!
}
...or you could check that your divisors are never zero before you attempt the operation.
if ((1 - (slope1 * slope2))==0)
{
return /*something meaningful to avoid the div by zero*/
}
else
{
double angle = Math.atan((slope1 - slope2) / (1 - (slope1 * slope2)));
return angle;
}
Check this Python code:
import math
def angle(x1,y1,x2,y2,x3,y3):
if (x1==x2==x3 or y1==y2==y3):
return 180
else:
dx1 = x2-x1
dy1 = y2-y1
dx2 = x3-x2
dy2 = y3-y2
if x1==x2:
a1=90
else:
m1=dy1/dx1
a1=math.degrees(math.atan(m1))
if x2==x3:
a2=90
else:
m2=dy2/dx2
a2=math.degrees(math.atan(m2))
angle = abs(a2-a1)
return angle
print angle(0,4,0,0,9,-6)
dx1=x2-x1 ; dy1=y2-y1 ; dx2=x4-x3 ;dy2=y4-y3.
Angle(L1,L2)=pi()/2*((1+sign(dx1))* (1-sign(dy1^2))-(1+sign(dx2))*(1-sign(dy2^2)))
+pi()/4*((2+sign(dx1))*sign(dy1)-(2+sign(dx2))*sign(dy2))
+sign(dx1*dy1)*atan((abs(dx1)-abs(dy1))/(abs(dx1)+abs(dy1)))
-sign(dx2*dy2)*atan((abs(dx2)-abs(dy2))/(abs(dx2)+abs(dy2)))

Categories