Calculating degrees to radians in terms of pi - java

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"

"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

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

How to convert radians to degrees

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

How do I fix this heart?

Seeing as Valentine's Day is fast approaching, I decided to create a heart. So I found this heart from mathematica.se:
I played around in Mathematica (solved for z, switching some variables around) to get this equation for the z-value of the heart, given the x and y values (click for full-size):
I faithfully ported this equation to Java, dealing with a couple out-of-bounds cases:
import static java.lang.Math.cbrt;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
...
public static double heart(double xi, double yi) {
double x = xi;
double y = -yi;
double temp = 5739562800L * pow(y, 3) + 109051693200L * pow(x, 2) * pow(y, 3)
- 5739562800L * pow(y, 5);
double temp1 = -244019119519584000L * pow(y, 9) + pow(temp, 2);
//
if (temp1 < 0) {
return -1; // this is one possible out of bounds location
// this spot is the location of the problem
}
//
double temp2 = sqrt(temp1);
double temp3 = cbrt(temp + temp2);
if (temp3 != 0) {
double part1 = (36 * cbrt(2) * pow(y, 3)) / temp3;
double part2 = 1 / (10935 * cbrt(2)) * temp3;
double looseparts = 4.0 / 9 - 4.0 / 9 * pow(x, 2) - 4.0 / 9 * pow(y, 2);
double sqrt_body = looseparts + part1 + part2;
if (sqrt_body >= 0) {
return sqrt(sqrt_body);
} else {
return -1; // this works; returns -1 if we are outside the heart
}
} else {
// through trial and error, I discovered that this should
// be an ellipse (or that it is close enough)
return Math.sqrt(Math.pow(2.0 / 3, 2) * (1 - Math.pow(x, 2)));
}
}
The only problem is that when temp1 < 0, I cannot simply return -1, like I do:
if (temp1 < 0) {
return -1; // this is one possible out of bounds location
// this spot is the location of the problem
}
That's not the behavior of the heart at that point. As it is, when I try to make my image:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import static java.lang.Math.cbrt;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
public class Heart {
public static double scale(int x, int range, double l, double r) {
double width = r - l;
return (double) x / (range - 1) * width + l;
}
public static void main(String[] args) throws IOException {
BufferedImage img = new BufferedImage(1000, 1000, BufferedImage.TYPE_INT_RGB);
// this is actually larger than the max heart value
final double max_heart = 0.679;
double max = 0.0;
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
double xv = scale(x, img.getWidth(), -1.2, 1.2);
double yv = scale(y, img.getHeight(), -1.3, 1);
double heart = heart(xv, yv); //this isn't an accident
// yes I don't check for the return of -1, but still
// the -1 values return a nice shade of pink: 0xFFADAD
// None of the other values should be negative, as I did
// step through from -1000 to 1000 in python, and there
// were no negatives that were not -1
int r = 0xFF;
int gb = (int) (0xFF * (max_heart - heart));
int rgb = (r << 16) | (gb << 8) | gb;
img.setRGB(x, y, rgb);
}
}
ImageIO.write(img, "png", new File("location"));
}
// heart function clipped; it belongs here
}
I get this:
Look at that dip at the top! I tried changing that problematic -1 to a .5, resulting in this:
Now the heart has horns. But it becomes clear where that problematic if's condition is met.
How can I fix this problem? I don't want a hole in my heart at the top, and I don't want a horned heart. If I could clip the horns to the shape of a heart, and color the rest appropriately, that would be perfectly fine. Ideally, the two sides of the heart would come together as a point (hearts have a little point at the join), but if they curve together like shown in the horns, that would be fine too. How can I achieve this?
The problem is simple. If we look at that horseshoe region, we get imaginary numbers. For part of it, it should belong to our heart. In that region, if we were to evaluate our function (by math, not by programming), the imaginary parts of the function cancel. So it should look like this (generated in Mathematica):
Basically, the function for that part is almost identical; we just have to do arithmetic with complex numbers instead of real numbers. Here's a function that does exactly that:
private static double topOfHeart(double x, double y, double temp, double temp1) {
//complex arithmetic; each double[] is a single number
double[] temp3 = cbrt_complex(temp, sqrt(-temp1));
double[] part1 = polar_reciprocal(temp3);
part1[0] *= 36 * cbrt(2) * pow(y, 3);
double[] part2 = temp3;
part2[0] /= (10935 * cbrt(2));
toRect(part1, part2);
double looseparts = 4.0 / 9 - 4.0 / 9 * pow(x, 2) - 4.0 / 9 * pow(y, 2);
double real_part = looseparts + part1[0] + part2[0];
double imag_part = part1[1] + part2[1];
double[] result = sqrt_complex(real_part, imag_part);
toRect(result);
// theoretically, result[1] == 0 should work, but floating point says otherwise
if (Math.abs(result[1]) < 1e-5) {
return result[0];
}
return -1;
}
/**
* returns a specific cuberoot of this complex number, in polar form
*/
public static double[] cbrt_complex(double a, double b) {
double r = Math.hypot(a, b);
double theta = Math.atan2(b, a);
double cbrt_r = cbrt(r);
double cbrt_theta = 1.0 / 3 * (2 * PI * Math.floor((PI - theta) / (2 * PI)) + theta);
return new double[]{cbrt_r, cbrt_theta};
}
/**
* returns a specific squareroot of this complex number, in polar form
*/
public static double[] sqrt_complex(double a, double b) {
double r = Math.hypot(a, b);
double theta = Math.atan2(b, a);
double sqrt_r = Math.sqrt(r);
double sqrt_theta = 1.0 / 2 * (2 * PI * Math.floor((PI - theta) / (2 * PI)) + theta);
return new double[]{sqrt_r, sqrt_theta};
}
public static double[] polar_reciprocal(double[] polar) {
return new double[]{1 / polar[0], -polar[1]};
}
public static void toRect(double[]... polars) {
for (double[] polar: polars) {
double a = Math.cos(polar[1]) * polar[0];
double b = Math.sin(polar[1]) * polar[0];
polar[0] = a;
polar[1] = b;
}
}
To join this with your program, simply change your function to reflect this:
if (temp1 < 0) {
return topOfHeart(x, y, temp, temp1);
}
And running it, we get the desired result:
It should be pretty clear that this new function implements exactly the same formula. But how does each part work?
double[] temp3 = cbrt_complex(temp, sqrt(-temp1));
cbrt_complex takes a complex number in the form of a + b i. That's why the second argument is simply sqrt(-temp1) (notice that temp1 < 0, so I use - instead of Math.abs; Math.abs is probably a better idea). cbrt_complex returns the cube root of the complex number, in polar form: r eiθ. We can see from wolframalpha that with positive r and θ, we can write an n-th root of a complex numbers as follows:
And that's exactly how the code for the cbrt_complex and sqrt_complex work. Note that both take a complex number in rectangular coordinates (a + b i) and return a complex number in polar coordinates (r eiθ)
double[] part1 = polar_reciprocal(temp3);
It is easier to take the reciprocal of a polar complex number than a rectangular complex number. If we have r eiθ, its reciprocal (this follows standard power rules, luckily) is simply 1/r e-iθ. This is actually why we are staying in polar form; polar form makes multiplication-type operations easier, and addition type operations harder, while rectangular form does the opposite.
Notice that if we have a polar complex number r eiθ and we want to multiply by a real number d, the answer is as simple as d r eiθ.
The toRect function does exactly what it seems like it does: it converts polar coordinate complex numbers to rectangular coordinate complex numbers.
You may have noticed that the if statement doesn't check that there is no imaginary part, but only if the imaginary part is really small. This is because we are using floating point numbers, so checking result[1] == 0 will likely fail.
And there you are! Notice that we could actually implement the entire heart function with this complex number arithmetic, but it's probably faster to avoid this.

How do I write a Java program that calculates the distance between two points on earth?

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

how to solve cos 90 problem in java? [duplicate]

This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 6 years ago.
I have some problems with calculating cosinus 90 in Java using Math.cos function :
public class calc{
private double x;
private double y;
public calc(double x,double y){
this.x=x;
this.y=y;
}
public void print(double theta){
x = x*Math.cos(theta);
y = y*Math.sin(theta);
System.out.println("cos 90 : "+x);
System.out.println("sin 90 : "+y);
}
public static void main(String[]args){
calc p = new calc(3,4);
p.print(Math.toRadians(90));
}
}
When I calculate cos90 or cos270, it gives me absurb values. It should be 0. I tested with 91 or 271, gives a near 0 which is correct.
what should I do to make the output of cos 90 = 0? so, it makes the output x = 0 and y = 4.
Thankful for advice
What you're getting is most likely very, very small numbers, which are being displayed in exponential notation. The reason you're getting them is because pi/2 is not exactly representable in IEEE 754 notation, so there's no way to get the exact cosine of 90/270 degrees.
Just run your source and it returns:
cos 90 : 1.8369701987210297E-16
sin 90 : 4.0
That's absolutely correct. The first value is nearly 0. The second is 4 as expected.
3 * cos(90°) = 3 * 0 = 0
Here you have to read the Math.toRadians() documentation which says:
Converts an angle measured in degrees to an approximately equivalent angle measured in radians. The conversion from degrees to radians is generally inexact.
Update: You can use for example the MathUtils.round() method from the Apache Commons repository and round the output to say 8 decimals, like this:
System.out.println("cos 90 : " + MathUtils.round(x, 8));
That will give you:
cos 90 : 0.0
sin 90 : 4.0
Try this:
public class calc
{
private double x;
private double y;
public calc(double x,double y)
{
this.x=x;
this.y=y;
}
public void print(double theta)
{
if( ((Math.toDegrees(theta) / 90) % 2) == 1)
{
x = x*0;
y = y*Math.sin(theta);
}
else if( ((Math.toDegrees(theta) / 90) % 2) == 0)
{
x = x*Math.cos(theta);
y = y*0;
}
else
{
x = x*Math.cos(theta);
y = y*Math.sin(theta);
}
System.out.println("cos 90 : "+x);
System.out.println("sin 90 : "+y);
}
public static void main(String[]args)
{
calc p = new calc(3,4);
p.print(Math.toRadians(90));
}
}

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