How do i print a line diagonally in python3? I would like to print the letter A. I am a new user to python - python-3.6

I would like to print the letter A. I am a new user to python. I am trying to use the following piece of code. How can i improve this?
letter_rep=['******']
for i in range(len(letter_rep)):
print('*'*i,letter_rep)

def print_A(w: int, h: int, char: str) -> None:
"""Print the letter 'A' as an ASCII art using char.
Play around with w and h to find the ideal dimenstion. A good starting
point can be w = 20, h = 10
:param w: Width of the canvas
:param h: Height of the canvas
:param char: Character used for the ASCII art.
"""
# Let the north west point of the canvas be the origin, we can generate
# the equations to compute the x coordinate based on the current y for the
# left and right strokes of the letter 'A'
left_stroke = lambda y: int((y + h) * w / (2 * h))
right_stroke = lambda y: int((h - y) * w / (2 * h))
mid_stroke_y: int = h // 2 # Set position of the horizontal stroke
for y in range(h):
# must use negative y due to the canvas being in the fourth quadrant
left_stroke_x = left_stroke(-y)
right_stroke_x = right_stroke(-y)
# The following print statements can be condensed to one line.
# It is expanded here for better explanation.
print(' ' * left_stroke_x, end='') # Empty spaces to the left of the left stroke
print(char, end='') # Left stroke
print( # Space between the left and right stroke
(right_stroke_x - left_stroke_x) * (char if y == mid_stroke_y else ' '),
end='',
)
print(char, end='') # Right stroke
print(' ' * (w - right_stroke_x)) # Empty spaces to the right of the right stroke
Example usage:
print_A(20, 10, '*')
'''
Output:
**
* *
* *
* *
* *
************
* *
* *
* *
* *
'''
print_A(40, 10, '#')
'''
Output:
##
# #
# #
# #
# #
######################
# #
# #
# #
# #
'''

Related

How to compute area in scilab and find points of intersections by an algorithm

This code represents the plot of the function g with two horizontal lines and one vertical line:
function y = g(x)
if x < 5 | 50 < x then
error("Out of range");
elseif x <= 11 then
y = -59.535905 + 24.763399 * x - 3.135727 * x^2 + 0.1288967 * x^3;
return;
elseif x <= 12 then
y = 1023.4465 - 270.59543 * x + 23.715076 * x^2 - 0.684764 * x^3;
return;
elseif x <= 17 then
y = -307.31448 + 62.094807 *x - 4.0091108 * x^2 + 0.0853523 * x^3;
return;
else
y = 161.42601 - 20.624104 * x + 0.8567075 * x^2 - 0.0100559 * x^3;
end
endfunction
**//this represents the vertical line**
a=linspace(45,45,60)
b=linspace(0,70,60)
plot(a,b,style='r')
**//this represents the first horizontal line**
a=linspace(0,60,60)
b=linspace(30,30,60)
plot(a,b,style='g')
//this represents the second horizontal line
a=linspace(0,60,60)
b=linspace(40,40,60)
plot(a,b,style='g')
//this is the graph of function "g"
t = [5:50];
plot(t, feval(t, g));
// the part of code is for to find the solution of fsolve
//plot(t, feval(t, g)-30);
//plot(t, feval(t, g)-60);
//deff('[y] = g2(x)', 'y = g(x)-30');
//deff('[y] = g3(x)', 'y = g(x)-40');
The problem is that I want to find the four points of intersection between the curve and the three lines and calculate the colored surface. and how can I colorful this area in Scilab because I used paint to better explain the figure. and welcome any help.
you just have to integrate max(0,min(g(x),40)-30) between x=45 and x=50.
integrate('max(0,min(g(x),40)-30)','x',45,50)
Before testing please change the first test of your g function to if 50 < x then (there is currently a bug in integrate, which calls the function to integrate with 1 as argument regardless of integration domain)

Convert Lat/Long to X,Y position within a Bounding Box

I have a bounding box of:
Left -122.27671
Bottom 37.80445
Right -122.26673
Top 37.81449
It could also be converted into NE Lat/Long and SW Lat/Long
Within that bounding box, I'd like to find the X,Y position of a specific Lat/Long. This would be using the Mercator projection.
I've seen answers that find the X,Y of a position on a world map using Mercator, but not within a specific lat/lon.
Any help appreciated!
UPDATE
Put this together from another question I saw. Can anyone validate if this seems legit?
map_width = 1240
map_height = 1279
map_lon_left = -122.296916
map_lon_right = -122.243380
map_lon_delta = map_lon_right - map_lon_left
map_lat_bottom = 37.782368
map_lat_bottom_degree = map_lat_bottom * Math::PI / 180
def convert_geo_to_pixel(lat, long)
x = (long - map_lon_left) * (map_width / map_lon_delta)
lat = lat * Math::PI / 180
world_map_width = ((map_width / map_lon_delta) * 360) / (2 * Math::PI)
map_offset_y = (world_map_width / 2 * Math.log((1 + Math.sin(map_lat_bottom_degree)) / (1 - Math.sin(map_lat_bottom_degree))))
y = map_height - ((world_map_width / 2 * Math.log((1 + Math.sin(lat)) / (1 - Math.sin(lat)))) - map_offset_y)
return [x, y]
end
Found a better solution that I've test and validated. Posting this for anyone else who might find it useful. It's written in Ruby but easy to convert to any other language
#north = to_radians(37.81449)
#south = to_radians(37.80445)
#east = to_radians(-122.26673)
#west = to_radians(-122.27671)
# Coordinates above are a subsection of Oakland, CA
#map_width = map_width
#map_height = map_height
def location_to_pixel(lat:, lon:)
lat = to_radians(lat)
lon = to_radians(lon)
ymin = mercator_y(#south)
ymax = mercator_y(#north)
x_factor = #map_width/(#east - #west)
y_factor = #map_height/(ymax - ymin)
y = mercator_y(lat);
x = (lon - #west) * x_factor
y = (ymax - y) * y_factor
[x, y]
end
def to_radians(deg)
deg * Math::PI/180
end
def mercator_y(lat)
Math.log(
Math.tan(lat/2 + Math::PI/4)
)
end
Let's s is shift of map in world space, bottom latitude in radians B, top latitude T. (I assume y=0 is bottom)
C * Sin(B) = 0 + s
C * Sin(T) = map_height + s
=>
C = map_height / (Sin(T) - Sin(B))
s = C * Sin(B)
y = C * Sin(Lat) - s =
C * Sin(Lat) - C * Sin(B) =
C * (Sin(Lat) - Sin(B)) =
map_height * (Sin(Lat) - Sin(B) / (Sin(T) - Sin(B))
// note - resembles linear interpolation is sine space

Uniformly distribute x points inside a circle

I would like to uniformly distribute a predetermined set of points within a circle. By uniform distribution, I mean they should all be equally distanced from each other (hence a random approach won't work). I tried a hexagonal approach, but I had problems consistently reaching the outermost radius.
My current approach is a nested for loop where each outer iteration reduces the radius & number of points, and each inner loop evenly drops points on the new radius. Essentially, it's a bunch of nested circles. Unfortunately, it's far from even. Any tips on how to do this correctly?
The goals of having a uniform distribution within the area and a uniform distribution on the boundary conflict; any solution will be a compromise between the two. I augmented the sunflower seed arrangement with an additional parameter alpha that indicates how much one cares about the evenness of boundary.
alpha=0 gives the typical sunflower arrangement, with jagged boundary:
With alpha=2 the boundary is smoother:
(Increasing alpha further is problematic: Too many points end up on the boundary).
The algorithm places n points, of which the kth point is put at distance sqrt(k-1/2) from the boundary (index begins with k=1), and with polar angle 2*pi*k/phi^2 where phi is the golden ratio. Exception: the last alpha*sqrt(n) points are placed on the outer boundary of the circle, and the polar radius of other points is scaled to account for that. This computation of the polar radius is done in the function radius.
It is coded in MATLAB.
function sunflower(n, alpha) % example: n=500, alpha=2
clf
hold on
b = round(alpha*sqrt(n)); % number of boundary points
phi = (sqrt(5)+1)/2; % golden ratio
for k=1:n
r = radius(k,n,b);
theta = 2*pi*k/phi^2;
plot(r*cos(theta), r*sin(theta), 'r*');
end
end
function r = radius(k,n,b)
if k>n-b
r = 1; % put on the boundary
else
r = sqrt(k-1/2)/sqrt(n-(b+1)/2); % apply square root
end
end
Might as well tag on my Python translation.
from math import sqrt, sin, cos, pi
phi = (1 + sqrt(5)) / 2 # golden ratio
def sunflower(n, alpha=0, geodesic=False):
points = []
angle_stride = 360 * phi if geodesic else 2 * pi / phi ** 2
b = round(alpha * sqrt(n)) # number of boundary points
for k in range(1, n + 1):
r = radius(k, n, b)
theta = k * angle_stride
points.append((r * cos(theta), r * sin(theta)))
return points
def radius(k, n, b):
if k > n - b:
return 1.0
else:
return sqrt(k - 0.5) / sqrt(n - (b + 1) / 2)
# example
if __name__ == '__main__':
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
points = sunflower(500, alpha=2, geodesic=False)
xs = [point[0] for point in points]
ys = [point[1] for point in points]
ax.scatter(xs, ys)
ax.set_aspect('equal') # display as square plot with equal axes
plt.show()
Stumbled across this question and the answer above (so all cred to user3717023 & Matt).
Just adding my translation into R here, in case someone else needed that :)
library(tibble)
library(dplyr)
library(ggplot2)
sunflower <- function(n, alpha = 2, geometry = c('planar','geodesic')) {
b <- round(alpha*sqrt(n)) # number of boundary points
phi <- (sqrt(5)+1)/2 # golden ratio
r <- radius(1:n,n,b)
theta <- 1:n * ifelse(geometry[1] == 'geodesic', 360*phi, 2*pi/phi^2)
tibble(
x = r*cos(theta),
y = r*sin(theta)
)
}
radius <- function(k,n,b) {
ifelse(
k > n-b,
1,
sqrt(k-1/2)/sqrt(n-(b+1)/2)
)
}
# example:
sunflower(500, 2, 'planar') %>%
ggplot(aes(x,y)) +
geom_point()
Building on top of #OlivelsAWord , here is a Python implementation using numpy:
import numpy as np
import matplotlib.pyplot as plt
def sunflower(n: int, alpha: float) -> np.ndarray:
# Number of points respectively on the boundary and inside the cirlce.
n_exterior = np.round(alpha * np.sqrt(n)).astype(int)
n_interior = n - n_exterior
# Ensure there are still some points in the inside...
if n_interior < 1:
raise RuntimeError(f"Parameter 'alpha' is too large ({alpha}), all "
f"points would end-up on the boundary.")
# Generate the angles. The factor k_theta corresponds to 2*pi/phi^2.
k_theta = np.pi * (3 - np.sqrt(5))
angles = np.linspace(k_theta, k_theta * n, n)
# Generate the radii.
r_interior = np.sqrt(np.linspace(0, 1, n_interior))
r_exterior = np.ones((n_exterior,))
r = np.concatenate((r_interior, r_exterior))
# Return Cartesian coordinates from polar ones.
return r * np.stack((np.cos(angles), np.sin(angles)))
# NOTE: say the returned array is called s. The layout is such that s[0,:]
# contains X values and s[1,:] contains Y values. Change the above to
# return r.reshape(n, 1) * np.stack((np.cos(angles), np.sin(angles)), axis=1)
# if you want s[:,0] and s[:,1] to contain X and Y values instead.
if __name__ == '__main__':
fig, ax = plt.subplots()
# Let's plot three sunflowers with different values of alpha!
for alpha in (0, 1, 2):
s = sunflower(500, alpha)
# NOTE: the 'alpha=0.5' parameter is to control transparency, it does
# not have anything to do with the alpha used in 'sunflower' ;)
ax.scatter(s[0], s[1], alpha=0.5, label=f"alpha={alpha}")
# Display as square plot with equal axes and add a legend. Then show the result :)
ax.set_aspect('equal')
ax.legend()
plt.show()
Adding my Java implementation of previous answers with an example (Processing).
int n = 2000; // count of nodes
Float alpha = 2.; // constant that can be adjusted to vary the geometry of points at the boundary
ArrayList<PVector> vertices = new ArrayList<PVector>();
Float scaleFactor = 200.; // scale points beyond their 0.0-1.0 range for visualisation;
void setup() {
size(500, 500);
// Test
vertices = sunflower(n, alpha);
displayTest(vertices, scaleFactor);
}
ArrayList<PVector> sunflower(int n, Float alpha) {
Double phi = (1 + Math.sqrt(5)) / 2; // golden ratio
Double angle = 2 * PI / Math.pow(phi, 2); // value used to calculate theta for each point
ArrayList<PVector> points = new ArrayList<PVector>();
Long b = Math.round(alpha*Math.sqrt(n)); // number of boundary points
Float theta, r, x, y;
for (int i = 1; i < n + 1; i++) {
r = radius(i, n, b.floatValue());
theta = i * angle.floatValue();
x = r * cos(theta);
y = r * sin(theta);
PVector p = new PVector(x, y);
points.add(p);
}
return points;
}
Float radius(int k, int n, Float b) {
if (k > n - b) {
return 1.0;
} else {
Double r = Math.sqrt(k - 0.5) / Math.sqrt(n - (b+1) / 2);
return r.floatValue();
}
}
void displayTest(ArrayList<PVector> points, Float size) {
for (int i = 0; i < points.size(); i++) {
Float x = size * points.get(i).x;
Float y = size * points.get(i).y;
pushMatrix();
translate(width / 2, height / 2);
ellipse(x, y, 5, 5);
popMatrix();
}
}
Here's my Unity implementation.
Vector2[] Sunflower(int n, float alpha = 0, bool geodesic = false){
float phi = (1 + Mathf.Sqrt(5)) / 2;//golden ratio
float angle_stride = 360 * phi;
float radius(float k, float n, float b)
{
return k > n - b ? 1 : Mathf.Sqrt(k - 0.5f) / Mathf.Sqrt(n - (b + 1) / 2);
}
int b = (int)(alpha * Mathf.Sqrt(n)); //# number of boundary points
List<Vector2>points = new List<Vector2>();
for (int k = 0; k < n; k++)
{
float r = radius(k, n, b);
float theta = geodesic ? k * 360 * phi : k * angle_stride;
float x = !float.IsNaN(r * Mathf.Cos(theta)) ? r * Mathf.Cos(theta) : 0;
float y = !float.IsNaN(r * Mathf.Sin(theta)) ? r * Mathf.Sin(theta) : 0;
points.Add(new Vector2(x, y));
}
return points.ToArray();
}

Perpendicular on a line segment from a given point

I want to calculate a point on a given line that is perpendicular from a given point.
I have a line segment AB and have a point C outside line segment. I want to calculate a point D on AB such that CD is perpendicular to AB.
I have to find point D.
It quite similar to this, but I want to consider to Z coordinate also as it does not show up correctly in 3D space.
Proof:
Point D is on a line CD perpendicular to AB, and of course D belongs to AB.
Write down the Dot product of the two vectors CD.AB = 0, and express the fact D belongs to AB as D=A+t(B-A).
We end up with 3 equations:
Dx=Ax+t(Bx-Ax)
Dy=Ay+t(By-Ay)
(Dx-Cx)(Bx-Ax)+(Dy-Cy)(By-Ay)=0
Subtitute the first two equations in the third one gives:
(Ax+t(Bx-Ax)-Cx)(Bx-Ax)+(Ay+t(By-Ay)-Cy)(By-Ay)=0
Distributing to solve for t gives:
(Ax-Cx)(Bx-Ax)+t(Bx-Ax)(Bx-Ax)+(Ay-Cy)(By-Ay)+t(By-Ay)(By-Ay)=0
which gives:
t= -[(Ax-Cx)(Bx-Ax)+(Ay-Cy)(By-Ay)]/[(Bx-Ax)^2+(By-Ay)^2]
getting rid of the negative signs:
t=[(Cx-Ax)(Bx-Ax)+(Cy-Ay)(By-Ay)]/[(Bx-Ax)^2+(By-Ay)^2]
Once you have t, you can figure out the coordinates for D from the first two equations.
Dx=Ax+t(Bx-Ax)
Dy=Ay+t(By-Ay)
function getSpPoint(A,B,C){
var x1=A.x, y1=A.y, x2=B.x, y2=B.y, x3=C.x, y3=C.y;
var px = x2-x1, py = y2-y1, dAB = px*px + py*py;
var u = ((x3 - x1) * px + (y3 - y1) * py) / dAB;
var x = x1 + u * px, y = y1 + u * py;
return {x:x, y:y}; //this is D
}
There is a simple closed form solution for this (requiring no loops or approximations) using the vector dot product.
Imagine your points as vectors where point A is at the origin (0,0) and all other points are referenced from it (you can easily transform your points to this reference frame by subtracting point A from every point).
In this reference frame point D is simply the vector projection of point C on the vector B which is expressed as:
// Per wikipedia this is more efficient than the standard (A . Bhat) * Bhat
Vector projection = Vector.DotProduct(A, B) / Vector.DotProduct(B, B) * B
The result vector can be transformed back to the original coordinate system by adding point A to it.
A point on line AB can be parametrized by:
M(x)=A+x*(B-A), for x real.
You want D=M(x) such that DC and AB are orthogonal:
dot(B-A,C-M(x))=0.
That is: dot(B-A,C-A-x*(B-A))=0, or dot(B-A,C-A)=x*dot(B-A,B-A), giving:
x=dot(B-A,C-A)/dot(B-A,B-A) which is defined unless A=B.
What you are trying to do is called vector projection
Here i have converted answered code from "cuixiping" to matlab code.
function Pr=getSpPoint(Line,Point)
% getSpPoint(): find Perpendicular on a line segment from a given point
x1=Line(1,1);
y1=Line(1,2);
x2=Line(2,1);
y2=Line(2,1);
x3=Point(1,1);
y3=Point(1,2);
px = x2-x1;
py = y2-y1;
dAB = px*px + py*py;
u = ((x3 - x1) * px + (y3 - y1) * py) / dAB;
x = x1 + u * px;
y = y1 + u * py;
Pr=[x,y];
end
I didn't see this answer offered, but Ron Warholic had a great suggestion with the Vector Projection. ACD is merely a right triangle.
Create the vector AC i.e (Cx - Ax, Cy - Ay)
Create the Vector AB i.e (Bx - Ax, By - Ay)
Dot product of AC and AB is equal to the cosine of the angle between the vectors. i.e cos(theta) = ACx*ABx + ACy*ABy.
Length of a vector is sqrt(x*x + y*y)
Length of AD = cos(theta)*length(AC)
Normalize AB i.e (ABx/length(AB), ABy/length(AB))
D = A + NAB*length(AD)
For anyone who might need this in C# I'll save you some time:
double Ax = ;
double Ay = ;
double Az = ;
double Bx = ;
double By = ;
double Bz = ;
double Cx = ;
double Cy = ;
double Cz = ;
double t = ((Cx - Ax) * (Bx - Ax) + (Cy - Ay) * (By - Ay)) / (Math.Pow(Bx - Ax, 2) + Math.Pow(By - Ay, 2));
double Dx = Ax + t*(Bx - Ax);
double Dy = Ay + t*(By - Ay);
Here is another python implementation without using a for loop. It works for any number of points and any number of line segments. Given p_array as a set of points, and x_array , y_array as continues line segments or a polyline.
This uses the equation Y = mX + n and considering that the m factor for a perpendicular line segment is -1/m.
import numpy as np
def ortoSegmentPoint(self, p_array, x_array, y_array):
"""
:param p_array: np.array([[ 718898.941 9677612.901 ], [ 718888.8227 9677718.305 ], [ 719033.0528 9677770.692 ]])
:param y_array: np.array([9677656.39934991 9677720.27550726 9677754.79])
:param x_array: np.array([718895.88881594 718938.61392781 718961.46])
:return: [POINT, LINE] indexes where point is orthogonal to line segment
"""
# PENDIENTE "m" de la recta, y = mx + n
m_array = np.divide(y_array[1:] - y_array[:-1], x_array[1:] - x_array[:-1])
# PENDIENTE INVERTIDA, 1/m
inv_m_array = np.divide(1, m_array)
# VALOR "n", y = mx + n
n_array = y_array[:-1] - x_array[:-1] * m_array
# VALOR "n_orto" PARA LA RECTA PERPENDICULAR
n_orto_array = np.array(p_array[:, 1]).reshape(len(p_array), 1) + inv_m_array * np.array(p_array[:, 0]).reshape(len(p_array), 1)
# PUNTOS DONDE SE INTERSECTAN DE FORMA PERPENDICULAR
x_intersec_array = np.divide(n_orto_array - n_array, m_array + inv_m_array)
y_intersec_array = m_array * x_intersec_array + n_array
# LISTAR COORDENADAS EN PARES
x_coord = np.array([x_array[:-1], x_array[1:]]).T
y_coord = np.array([y_array[:-1], y_array[1:]]).T
# FILAS: NUMERO DE PUNTOS, COLUMNAS: NUMERO DE TRAMOS
maskX = np.where(np.logical_and(x_intersec_array < np.max(x_coord, axis=1), x_intersec_array > np.min(x_coord, axis=1)), True, False)
maskY = np.where(np.logical_and(y_intersec_array < np.max(y_coord, axis=1), y_intersec_array > np.min(y_coord, axis=1)), True, False)
mask = maskY * maskX
return np.argwhere(mask == True)
As Ron Warholic and Nicolas Repiquet answered, this can be solved using vector projection. For completeness I'll add a python/numpy implementation of this here in case it saves anyone else some time:
import numpy as np
# Define some test data that you can solve for directly.
first_point = np.array([4, 4])
second_point = np.array([8, 4])
target_point = np.array([6, 6])
# Expected answer
expected_point = np.array([6, 4])
# Create vector for first point on line to perpendicular point.
point_vector = target_point - first_point
# Create vector for first point and second point on line.
line_vector = second_point - first_point
# Create the projection vector that will define the position of the resultant point with respect to the first point.
projection_vector = (np.dot(point_vector, line_vector) / np.dot(line_vector, line_vector)) * line_vector
# Alternative method proposed in another answer if for whatever reason you prefer to use this.
_projection_vector = (np.dot(point_vector, line_vector) / np.linalg.norm(line_vector)**2) * line_vector
# Add the projection vector to the first point
projected_point = first_point + projection_vector
# Test
(projected_point == expected_point).all()
Since you're not stating which language you're using, I'll give you a generic answer:
Just have a loop passing through all the points in your AB segment, "draw a segment" to C from them, get the distance from C to D and from A to D, and apply pithagoras theorem. If AD^2 + CD^2 = AC^2, then you've found your point.
Also, you can optimize your code by starting the loop by the shortest side (considering AD and BD sides), since you'll find that point earlier.
Here is a python implementation based on Corey Ogburn's answer from this thread.
It projects the point q onto the line segment defined by p1 and p2 resulting in the point r.
It will return null if r falls outside of line segment:
def is_point_on_line(p1, p2, q):
if (p1[0] == p2[0]) and (p1[1] == p2[1]):
p1[0] -= 0.00001
U = ((q[0] - p1[0]) * (p2[0] - p1[0])) + ((q[1] - p1[1]) * (p2[1] - p1[1]))
Udenom = math.pow(p2[0] - p1[0], 2) + math.pow(p2[1] - p1[1], 2)
U /= Udenom
r = [0, 0]
r[0] = p1[0] + (U * (p2[0] - p1[0]))
r[1] = p1[1] + (U * (p2[1] - p1[1]))
minx = min(p1[0], p2[0])
maxx = max(p1[0], p2[0])
miny = min(p1[1], p2[1])
maxy = max(p1[1], p2[1])
is_valid = (minx <= r[0] <= maxx) and (miny <= r[1] <= maxy)
if is_valid:
return r
else:
return None

Drawing a triangle in a coordinate plane given its three sides

The length of three sides of the triangle, a, b and c will be given, and I need to find the coordinates of the vertices. The center (probably the circumcenter) can either be the origin or (x,y).
Can anyone point me in the right direction?
I've read brainjam's answer and checked whether his answer is true and he is right.
Calculation:
O(0;0), A(a;0) and B(x;y) are the three points of the triangle. C1 is the circle around A and r1 = c; C2 is the circle around O and r2 = b. B(X;Y) is the intersection of C1 and C2, which means that the point is on both of the circles.
C1: (x - a) * (x - a) + y * y = c * c
C2: x * x + y * y = b * b
y * y = b * b - x * x
(x - a) * (x - a) + b * b - x * x = c * c
x * x - 2 * a * x + a * a + b * b - x * x - c * c = 0
2 * a * x = (a * a + b * b - c * c)
x = (a * a + b * b - c * c) / (2 * a)
y * y = b * b - ((a * a + b * b - c * c) / (2 * a)) * ((a * a + b * b - c * c) / (2 * a))
y = +- sqrt(b * b - ((a * a + b * b - c * c) / (2 * a)) * ((a * a + b * b - c * c) / (2 * a)))
Place the first vertex at the origin (0,0). Place the second vertex at (a,0). To compute the third vertex, find the intersection of the two circles with centers (0,0) and (a,0) and radii b and c.
Update: Lajos Arpad has given the details of computing the location of the third point in this answer. It boils down to (x,y) where x = (b2+a2-c2)/2a and y=Âħsqrt(b2-x2)
This question and the answers helped me out today in implementing this. It will calculate the unknown vertices, "c" of circle intersections given 2 known points (a, b) and the distances (ac_length, bc_length) to the 3rd unknown vertex, "c".
Here is my resulting python implementation for anyone interested.
I also referenced the following:
http://mathworld.wolfram.com/RadicalLine.html
http://mathworld.wolfram.com/Circle-CircleIntersection.html
Using django's geos module for the Point() object, which could be replaced with shapely, or point objects removed altogether really.
from math import sqrt
from django.contrib.gis.geos import Point
class CirclesSeparate(BaseException):
pass
class CircleContained(BaseException):
pass
def discover_location(point_a, point_b, ac_length, bc_length):
"""
Find point_c given:
point_a
point_b
ac_length
bc_length
point_d == point at which the right-angle to c is formed.
"""
ab_length = point_a.distance(point_b)
if ab_length > (ac_length + bc_length):
raise CirclesSeparate("Given points do not intersect!")
elif ab_length < abs(ac_length - bc_length):
raise CircleContained("The circle of the points do not intersect")
# get the length to the vertex of the right triangle formed,
# by the intersection formed by circles a and b
ad_length = (ab_length**2 + ac_length**2 - bc_length**2)/(2.0 * ab_length)
# get the height of the line at a right angle from a_length
h = sqrt(abs(ac_length**2 - ad_length**2))
# Calculate the mid point (point_d), needed to calculate point_c(1|2)
d_x = point_a.x + ad_length * (point_b.x - point_a.x)/ab_length
d_y = point_a.y + ad_length * (point_b.y - point_a.y)/ab_length
point_d = Point(d_x, d_y)
# get point_c location
# --> get x
c_x1 = point_d.x + h * (point_b.y - point_a.y)/ab_length
c_x2 = point_d.x - h * (point_b.y - point_a.y)/ab_length
# --> get y
c_y1 = point_d.y - h * (point_b.x - point_a.x)/ab_length
c_y2 = point_d.y + h * (point_b.x - point_a.x)/ab_length
point_c1 = Point(c_x1, c_y1)
point_c2 = Point(c_x2, c_y2)
return point_c1, point_c2
When drawing an unknown triangle, it's usually easiest to pick one side (say, the longest) and place it horizontally or vertically. The endpoints of that side make up two of the triangle's vertices, and you can calculate the third by subdividing the triangle into two right triangles (the other two sides are the hypotenuses) and using the inverse sine/cosine functions to figure out the missing angles. By subdividing into right triangles, I mean something that looks like the image here: http://en.wikipedia.org/wiki/File:Triangle.TrigArea.svg Your first side would be AC in that drawing.
Once you have the triangle figured out, it should be easy to calculate it's center and translate it so that it is centered on whatever arbitrary center point you like.
First check the that the triangle is possible:
a+b >= c
b+c >= a
c+a >= b
Then, if it is, solve for the intersection of the two circles. The basic vertices are
{0,0}, {a,0}, {x,y}
where
x = (a^2-b^2+c^2)/(2a)
y = sqrt(c^2-x^2)
Finding the circumcenter is pretty easy from this point.

Resources