How to count length of a triangle when hypotenuse is given - python

I have to count the length of a triangle with 90°, 45°, 45° angles when I only know the hypotenuse. That is what I have done yet.
def tr(b):
a = sqrt(b*b+b*b)/2
fd(b)
lt(135)
fd(a)
lt(90)
fd(a)
lt(135)

The isosceles right-angled triangle is the right-angled triangle with two equal cathets, then:
It has two angles of 45 °
It is half a square
In fact, for the corners we will have:
Right angle = 90 °
Angles at the base of the isosceles triangle = 90 ° / 2 = 45 °
For the sides we will have that, called a the cateti and b the hypotenuse is worth the theorem of Pythagoras then:
a^2 + a^2 = b^2 2a^2 = b^2
therefore being known the value d of the hypotenuse we will have
a^2 = b^2 / 2 a = sqrt(b^2 / 2) a = b / sqrt(2) rationalize and I
get a = b*sqrt(2)/2
a=b*2**0.5/2
Being instead known the value a of the cateto we will have
b=a*2**0.5

Related

Move in a serpentine line or snake line

A car should go from A to B. But not in the direct line. As in reality, it should drive in 2 arcs as shown in the diagram. Is there some kind of function for this? How would it be used?
You can consider this as an ellipse and calculate the perimeter of ellipse by giving length and magnitude, you can get your path length
import math
def calculate_perimeter(a,b):
perimeter = math.pi * ( 3*(a+b) - math.sqrt( (3*a + b) * (a + 3*b) ) )
return perimeter
calculate_perimeter(distance/2, magnitude_of_deviation/2)
Edit
distance = absolute(p1-p2)
= math.sqrt((x2-x1)**2 + (y2-y1)**2)
you have start p1(x,y) and p2 (x2,y2), absolute distance is distance at here and deviation magnitude is your choice and one eclipse would work for all distance

How do I draw this shape in Turtle? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
The community reviewed whether to reopen this question 8 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I got a challenge in a learning group today to draw this shape in python turtle library.
I cannot figure out a way to express the geometrical solution to find the angles to turn and the size of the line I need.
Can you please tell me how to draw the first polygon alone? I already know how to make the pattern.
I am in fifth grade. So please give me a solution that I can understand.
Here is the solution I came up with. It is based on this diagram:
Math background
My solution uses "trigonometry", which is a method for calculating the length of one side of a triangle from the length of another side and the angles of the triangle. This is advanced math which I would expect to be taught maybe in 9th or 10th grade. I do not expect someone in 5th grade to know trigonometry. Also I cannot explain every detail of trigonometry, because I would have to write a lot and I do not think I have the teaching skills to make it clear. I would recommend you to look at for example this video to learn about the method:
https://www.youtube.com/watch?v=5tp74g4N8EY
You could also ask your teacher for more information, or research about it on the internet on your own.
Step 1: Calculating the angles
We can do this without trigonometry.
First, we see there is a "pentagon" (5-sided polygon) in the middle. I want to know the inner angle of a corner in this "pentagon". I call this angle X:
How can we calculate the angle X? We first remember that the sum of the inner angles in a triangle is 180°. We see that we can divide a 5-sides polygon into 5-2 triangles like this:
The sum of the inner angle of each of these 5-2 triangles is 180°. So for the whole 5-sided polygon, the sum of the inner angles is 180° * (5-2). Since all angles have the same size, each angle is 180°*(5-2) / 5 = 108°. So we have X = 108°.
The angle on the other side is the same as X. This allows us the calculate the angle between the two X. I will call this angle Y:
Since a full circle is 360°, we know that 360° = 2*X + 2*Y. Therefore, Y = (360° - 2*X) / 2. We know that X = 108°, so we get Y = 72°.
Next, we see there is a triangle containing the Y angle. I want to know the angle Z at the other corner of the triangle:
The inner angles of a triangle sum up to 180°*(3-2) = 180°. Therefore, we know that 180° = 2*Y + Z, so Z = 180° - 2*Y. We know that Y = 72°, so we get Z = 36°.
We will use the angle Z a lot. You can see that every corner of the green star has angle Z. The blue star is the same as the green star except it is rotated, so all blue corners also have angle Z. The corners of the red star are twice as wide as the corners of the green and blue stars, so the corners of the red star have the angle 2*Z.
Step 2: Calculating the lengths
First, we observe that all outer corners are on a circle. We call the radius of this circle R. We do not have to calculate R. Instead, we can take any value we want for R. We will always get the same shape but in different sizes. We could call R a "parameter" of the shape.
Given some value for R, I want to know the following lengths:
Calculating A:
We start with A. We can see the following triangle:
The long side of the triangle is our radius R. The other side has length A/2 and we do not care about the third side. The angle in the right-most corner is Z/2 (with Z = 36° being the angle we calculated in the previous section). The angle S is a right-angle, so S = 90°. We can calculate the third angle T because we know that the inner angles of a triangle sum up to 180°. Therefore, 180° = S + Z/2 + T. Solving for T, we get T = 180° - S - Z/2 = 180° - 90° - 36°/2 = 72°.
Next, we use trigonometry to calculate A/2. Trigonometry teaches us that A/2 = R * sin(T). Putting in the formula for T, we get A/2 = R * sin(72°). Solving for A, we get A = 2*R*sin(72°).
If you pick some value for R, for example R = 100, you can now calculate A with this formula. You would need a calculator for sin(72°), because it would be extremely difficult to calculate this in your head. Putting sin(72) into my calculator gives me 0.951056516. So for our choice R = 100, we know that A = 2 * R * sin(72°) = 2 * 100 * 0.951056516 = 190.211303259.
Calculating B:
We use the same technique to find a formula for B. We see the following triangle:
So the bottom side is the length of our radius R. The right side is B/2. We do not care about the third side. The right-most angle is three times Z/2. The angle S is a right-angle, so we have S = 90°. We can calculate the remaining angle T with 180° = S + T + 3*Z/2. Solving for T, we get T = 180° - S - 3*Z/2 = 180° - 90° - 3*36°/2 = 36°. Ok so T = Z, we could have also seen this from the picture, but now we have calculated it anyways.
Using trigonometry, we know that B/2 = R * sin(T), so we get the formula B = 2 * R * sin(36°) to calculate B for some choice of R.
Calculating C:
We see the following triangle:
So the bottom side has length A/2 and the top side has length B. We already have formulas for both of these sides. The third side is C, for which we want to find a formula. The right-most angle is Z. The angle S is a right-angle, so S = 90°. The top-most angle is three times Z/2.
Using trigonometry, we get C = sin(Z) * B.
Calculating D:
We see the following triangle:
We already have a formula for C. We want to find a formula for D. The top-most angle is Z/2 (I could not fit the text into the triangle). The bottom-left angle S is a right-angle.
Using trigonometry, we know that D = tan(Z/2) * C. The tan function is similar to the sin from the previous formulas. You can again put it into your calculator to compute the value, so for Z = 36°, I can put tan(36/2) into my calculator and it gives me 0.324919696.
Calculating E:
Ok this is easy, E = 2*D.
Halfway done already!
Calculating F:
This is similar to A and B:
We want to find a formula for F. The top side has length F/2. The bottom side has the length of our radius R. The right-most corner has angle Z. S is a right-angle. We can calculate T = 180° - S - Z = 180° - 90° - Z = 90° - Z.
Using trigonometry, we get F/2 = R * sin(T). Putting in the formula for T gives us F/2 = R*sin(90° - Z). Solving for F gives us F = 2*R*sin(90°-Z).
Calculating G:
We see the following triangle:
The top side has length F, we already know a formula for it. The right side has length G, we want to find a formula for it. We do not care about the bottom side. The left-most corner has angle Z/2. The right-most corner has angle 2*Z. The bottom corner has angle S, which is a right-angle, so S = 90°. It was not immediately obvious to me that the red line and the green line are perfectly perpendicular to each other so that S really is a right-angle, but you can verify this by using the formula for the inner angles of a triangle, which gives you 180° = Z/2 + 2*Z + S. Solving for S gives us S = 180° - Z/2 - 2*Z. Using Z = 36°, we get S = 180° - 36°/2 - 2* 36° = 90°.
Using trigonometry, we get G = F * sin(Z/2).
Calculating H:
We see the following triangle:
The right side has length G, we already have formula for that. The bottom side has length H, we want to find a formula for that. We do not care about the third side. The top corner has angle Z, the bottom-right corner has angle S. We already know that S is a right-angle from the last section.
Using trigonometry, we get H = G * tan(Z).
Calculating I:
This is easy, I is on the same line as A. We can see that A can be divided into A = I + H + E + H + I. We can simplify this to A = 2*I + 2*H + E. Solving for I gives us I = (A - 2*H - E)/2.
Calculating J:
Again this is easy, J is on the same line as F. We can see that F can be divided into F = G + J + G. We can simplify that to F = 2*G + J. Solving for J gives us J = F - 2*G.
Writing the Python program
We now have formulas for all the lines we were interested in! We can now put these into a Python program to draw the picture.
Python gives you helper functions for computing sin and tan. They are contained in the math module. So you would add import math to the top of your program, and then you can use math.sin(...) and math.tan(...) in your program. However, there is one problem: These Python functions do not use degrees to measure angles. Instead they use a different unit called "radians". Fortunately, it is easy to convert between degrees and radians: In degrees a full circle is 360°. In radians, a full circle is 2*pi, where pi is a special constant that is approximately 3.14159265359.... Therefore, we can convert an angle that is measured in degrees into an angle that is measured in radians, by dividing the angle by 360° and then multiplying it by 2*pi. We can write the following helper functions in Python:
import math
def degree_to_radians(angle_in_degrees):
full_circle_in_degrees = 360
full_circle_in_radians = 2 * math.pi
angle_in_radians = angle_in_degrees / full_circle_in_degrees * full_circle_in_radians
return angle_in_radians
def sin_from_degrees(angle_in_degrees):
angle_in_radians = degree_to_radians(angle_in_degrees)
return math.sin(angle_in_radians)
def tan_from_degrees(angle_in_degrees):
angle_in_radians = degree_to_radians(angle_in_degrees)
return math.tan(angle_in_radians)
We can now use our functions sin_from_degrees and tan_from_degrees to compute sin and tan from angles measured in degrees.
Putting it all together:
from turtle import *
import math
# Functions to calculate sin and tan ###########################################
def degree_to_radians(angle_in_degrees):
full_circle_in_degrees = 360
full_circle_in_radians = 2 * math.pi
angle_in_radians = angle_in_degrees / full_circle_in_degrees * full_circle_in_radians
return angle_in_radians
def sin_from_degrees(angle_in_degrees):
angle_in_radians = degree_to_radians(angle_in_degrees)
return math.sin(angle_in_radians)
def tan_from_degrees(angle_in_degrees):
angle_in_radians = degree_to_radians(angle_in_degrees)
return math.tan(angle_in_radians)
# Functions to calculate the angles ############################################
def get_X():
num_corners = 5
return (num_corners-2)*180 / num_corners
def get_Y():
return (360 - 2*get_X()) / 2
def get_Z():
return 180 - 2*get_Y()
# Functions to calculate the lengths ###########################################
def get_A(radius):
Z = get_Z()
return 2 * radius * sin_from_degrees(90 - Z/2)
def get_B(radius):
Z = get_Z()
return 2 * radius * sin_from_degrees(90 - 3*Z/2)
def get_C(radius):
Z = get_Z()
return sin_from_degrees(Z) * get_B(radius)
def get_D(radius):
Z = get_Z()
return tan_from_degrees(Z/2) * get_C(radius)
def get_E(radius):
return 2 * get_D(radius)
def get_F(radius):
Z = get_Z()
return 2 * radius * sin_from_degrees(90 - Z)
def get_G(radius):
Z = get_Z()
return get_F(radius) * sin_from_degrees(Z/2)
def get_H(radius):
Z = get_Z()
return get_G(radius) * tan_from_degrees(Z)
def get_I(radius):
A = get_A(radius)
E = get_E(radius)
H = get_H(radius)
return (A - E - 2*H) / 2
def get_J(radius):
F = get_F(radius)
G = get_G(radius)
return F - 2*G
# Functions to draw the stars ##################################################
def back_to_center():
penup()
goto(0, 0)
setheading(0)
pendown()
def draw_small_star(radius):
penup()
forward(radius)
pendown()
Z = get_Z()
left(180)
right(Z/2)
E = get_E(radius)
H = get_H(radius)
I = get_I(radius)
for i in range(0,5):
penup()
forward(I)
pendown()
forward(H)
penup()
forward(E)
pendown()
forward(H)
penup()
forward(I)
left(180)
right(Z)
back_to_center()
def draw_green_star(radius):
pencolor('green')
draw_small_star(radius)
def draw_blue_star(radius):
pencolor('blue')
Z = get_Z()
left(Z)
draw_small_star(radius)
def draw_red_star(radius):
pencolor('red')
Z = get_Z()
penup()
forward(radius)
pendown()
left(180)
right(Z)
G = get_G(radius)
J = get_J(radius)
for i in range(0,10):
pendown()
forward(G)
penup()
forward(J)
pendown()
forward(G)
left(180)
right(2*Z)
back_to_center()
def draw_shape(radius):
draw_green_star(radius)
draw_blue_star(radius)
draw_red_star(radius)
radius = 400
draw_shape(radius)
done()
Output:
Here's a different solution. It's based on a kite polygon where the upper portion is a pair of 3-4-5 right triangles and the lower portion is a pair of 8-15-17 right triangles:
from turtle import Screen, Turtle
KITES = 10
RADIUS = 100
def kite(t):
t.right(37)
t.forward(100)
t.right(81)
t.forward(170)
t.right(124)
t.forward(170)
t.right(81)
t.forward(100)
t.right(37)
turtle = Turtle()
turtle.penup()
turtle.sety(-RADIUS)
for _ in range(KITES):
turtle.circle(RADIUS, extent=180/KITES)
turtle.pendown()
kite(turtle)
turtle.penup()
turtle.circle(RADIUS, extent=180/KITES)
turtle.hideturtle()
screen = Screen()
screen.exitonclick()
(Yes, I'm obsessed with this puzzle.) I was sufficiently impressed by the brevity of #AnnZen's solution, I decided to see if I could come up with an even shorter one. The only unique structure in this polygon is the side of the kite:
So the problem becomes drawing ten of these in a circular fashion, and then reversing the code to draw them again in the opposite direction:
from turtle import *
for _ in range(2):
for _ in range(10):
fd(105)
lt(90)
fd(76.5)
pu()
bk(153)
rt(54)
pd()
lt(72)
lt, rt = rt, lt
done()
My Short code:
from turtle import *
for f, t in [(0,-72),(71,108),(71,0)]*10+[(29,90),(73,72),(73,90),(29,72)]*10:fd(f),rt(t)
Here's the solution:
import turtle
#turtle.tracer(0)
a = turtle.Turtle()
for _ in range(10):
a.forward(100)
a.right(90)
a.forward(73)
a.right(72)
a.forward(73)
a.backward(73)
a.right(108)
a.forward(73)
a.right(90)
a.penup()
a.forward(100)
a.pendown()
a.forward(100)
a.right(108)
#turtle.update()
Let's look at a yet another approach to drawing this shape. We'll start with the same diagram as #f9c69e9781fa194211448473495534
Using a ruler (1" = 100px) and protractor on the OP's original image, we can approximate this diagram with very simple code:
from turtle import Screen, Turtle
turtle = Turtle()
turtle.hideturtle()
turtle.penup() # center on the screen
turtle.setposition(-170, -125)
turtle.pendown()
for _ in range(10):
turtle.forward(340)
turtle.left(126)
turtle.forward(400)
turtle.left(126)
screen = Screen()
screen.exitonclick()
This is equivalent to drawing with a pencil and not lifting it nor overdrawing (backing up) on any line.
To make the shape we want pop out, we divide the two lines that we draw above into segments that are thinner and thicker. The first line breaks into three segments and the second into five:
To do this, we simply break the forward() calls in our loop into wide and narrow segments:
for _ in range(10):
turtle.width(4)
turtle.forward(105)
turtle.width(1)
turtle.forward(130)
turtle.width(4)
turtle.forward(105)
turtle.left(126)
turtle.width(1)
turtle.forward(76.5)
turtle.width(4)
turtle.forward(76.5)
turtle.width(1)
turtle.forward(94)
turtle.width(4)
turtle.forward(76.5)
turtle.width(1)
turtle.forward(76.5)
turtle.left(126)
Finally, we replace the thickness changes with lifting and lowering the pen:
Which is simply a matter of replacing the width() calls with penup() and pendown():
for _ in range(10):
turtle.pendown()
turtle.forward(105)
turtle.penup()
turtle.forward(130)
turtle.pendown()
turtle.forward(105)
turtle.left(126)
turtle.penup()
turtle.forward(76.5)
turtle.pendown()
turtle.forward(76.5)
turtle.penup()
turtle.forward(94)
turtle.pendown()
turtle.forward(76.5)
turtle.penup()
turtle.forward(76.5)
turtle.left(126)

Calculating the exact length of an SVG Arc in Python?

I want to be able to calculate the exact length of an SVG Arc. I can do all the manipulations rather easily. But, I am unsure of whether there is a solution at all or the exact implementation of the solution.
Here's the exact solution for the circumference of the ellipse. Using popular libraries is fine. I fully grasp that there are no easy solution as they will all require hypergeometric functions to be exact.
from scipy import pi, sqrt
from scipy.special import hyp2f1
def exact(a, b):
t = ((a - b) / (a + b)) ** 2
return pi * (a + b) * hyp2f1(-0.5, -0.5, 1, t)
a = 2.667950e9
b = 6.782819e8
print(exact(a, b))
My idea is to have this as opt-in code if you happen to have scipy installed it'll use the exact super-fancy solution, else it'll fall back to the weaker approximation code (progressively smaller line segments until error is small). The problem is the math level here is above me. And I don't know if there's some ways to specify a start and stop point for that.
Most of the approximation solutions are for ellipses, but I only want the arc. There may also be a solution unknown to me, for calculating the length of an arc on an ellipse but since the start and end position can be anywhere. It doesn't seem to be instantly viable to say a sweep angle is 15% of the total possible angle therefore it's 15% of the ellipse circumference.
A more effective less fancy arc approximation might also be nice. There are progressively better ellipse approximations but I can't go from ellipse circumference to arc length, so those are currently not helpful.
Let's say the arc parameterization is the start and end points on the ellipse. Since that's how SVG is parameterized. But, anything that isn't tautological like arc_length parameterization is a correct answer.
If you want to calculate this with your bare hands and the std lib, you can base your calculation on the following formula. This is only valid for two points on the upper half of the ellipse because of the acos but we're going to use it with the angles directly.
The calculation consists in these steps:
Start with the SVG data: start point, a ,b rotation, long arc, sweep, end point
Rotate the coordinate system to match the horizontal axis of the ellipse.
Solve a system of 4 equations with 4 unknowns to get the centre point and the angles corresponding to the start and end point
Approximate the integral by a discreet sum over small segments. This is where you could use scipy.special.ellipeinc, as suggested in the comments.
Step 2 is easy, just use a rotation matrix (note the angle rot is positive in the clockwise direction):
m = [
[math.cos(rot), math.sin(rot)],
[-math.sin(rot), math.cos(rot)]
]
Step 3 is very well explained in this answer. Note the value obtained for a1 is modulo pi because it is obtained with atan. That means that you need to calculate the centre points for the two angles t1 and t2 and check they match. If they don't, add pi to a1 and check again.
Step 4 is quite straightforward. Divide the interval [t1, t2] into n segments, get the value of the function at the end of each segment, time it by the segment length and sum all this up. You can try refining this by taking the value of the function at the mid-point of each segment, but I'm not sure there is much benefit to that. The number of segments is likely to have more effect on the precision.
Here is a very rough Python version of the above (please bear with the ugly coding style, I was doing this on my mobile whilst traveling 🤓)
import math
PREC = 1E-6
# matrix vector multiplication
def transform(m, p):
return ((sum(x * y for x, y in zip(m_r, p))) for m_r in m)
# the partial integral function
def ellipse_part_integral(t1, t2, a, b, n=100):
# function to integrate
def f(t):
return math.sqrt(1 - (1 - a**2 / b**2) * math.sin(t)**2)
start = min(t1, t2)
seg_len = abs(t1 - t2) / n
return - b * sum(f(start + seg_len * (i + 1)) * seg_len for i in range(n))
def ellipse_arc_length(x1, y1, a, b, rot, large_arc, sweep, x2, y2):
if abs(x1 - x2) < PREC and abs(y1 - y2) < PREC:
return 0
# get rot in radians
rot = math.pi / 180 * rot
# get the coordinates in the rotated coordinate system
m = [
[math.cos(rot), math.sin(rot)],
[- math.sin(rot), math.cos(rot)]
]
x1_loc, y1_loc, x2_loc, y2_loc = *transform(m, (x1,y1)), *transform(m, (x2,y2))
r1 = (x1_loc - x2_loc) / (2 * a)
r2 = (y2_loc - y1_loc) / (2 * b)
# avoid division by 0 if both points have same y coord
if abs(r2) > PREC:
a1 = math.atan(r1 / r2)
else:
a1 = r1 / abs(r1) * math.pi / 2
if abs(math.cos(a1)) > PREC:
a2 = math.asin(r2 / math.cos(a1))
else:
a2 = math.asin(r1 / math.sin(a1))
# calculate the angle of start and end point
t1 = a1 + a2
t2 = a1 - a2
# calculate centre point coords
x0 = x1_loc - a * math.cos(t1)
y0 = y1_loc - b * math.sin(t1)
x0s = x2_loc - a * math.cos(t2)
y0s = y2_loc - b * math.sin(t2)
# a1 value is mod pi so the centres may not match
# if they don't, check a1 + pi
if abs(x0 - x0s) > PREC or abs(y0 - y0s) > PREC:
a1 = a1 + math.pi
t1 = a1 + a2
t2 = a1 - a2
x0 = x1_loc - a * math.cos(t1)
y0 = y1_loc - b * math.sin(t1)
x0s = x2_loc - a * math.cos(t2)
y0s = y2_loc - b * math.sin(t2)
# get the angles in the range [0, 2 * pi]
if t1 < 0:
t1 += 2 * math.pi
if t2 < 0:
t2 += 2 * math.pi
# increase minimum by 2 * pi for a large arc
if large_arc:
if t1 < t2:
t1 += 2 * math.pi
else:
t2 += 2 * math.pi
return ellipse_part_integral(t1, t2, a, b)
print(ellipse_arc_length(0, 0, 40, 40, 0, False, True, 80, 0))
The good news is that the sweep flag doesn't matter as long as you're just looking for the length of the arc.
I'm not 100% sure the modulo pi problem is handled correctly and the implementation above may have a few bugs.
Nevertheless, it gave me a good approximation of the length in the simple case of a half circle, so I dare calling it WIP. Let me know if this is worth pursuing, I can have a further look when I'll be seated at a computer. Or maybe someone can come up with a clean way of doing this in the meantime?

is there a way to examine if an angle is a right angle programmatically?

i plot an angle in python
here is the code
x = [0,0.5,1]
y = [0,0.5,0]
plt.scatter(x,y)
plt.plot(x,y)
plt.show()
is there a way to examine if the angle is a right angle programmatically?
The easiest way is to test if the dot product of the vectors is 0.
In your case, you simply compute:
v1 = ( (x[1]-x[0]), (y[1]-y[0]) ) <- (0.5, 0.5)
v2 = ( (x[2]-x[1]), (y[2]-y[1]) ) <- (0.5, -0.5)
dot_product = v1[0]*v2[0] + v1[1]*v2[1] <- 0.5² - 0.5² = 0
The other answers do not really care about possible inaccuracies and truncation errors, nor efficiency.
Rather than an exact comparison to 90° (or 0° in case of dot product), it is wiser to check for a small angle difference to 90° (resp. 0°).
Also wise to avoid divisions, square roots and trigonometric functions. The cross-product method is among the most attractive.
Compute the cross-product of the sides of the angle and their squared lengths, and compare
with a precomputed tolerance:
(ABx . BCy - ABy . BCx)² ≥ α.(ABx² + ABy²).(BCx² + BCy²)
with α = cos²δ where δ is the angle tolerance.
You can try to calculate the angle, but an easier way could be to check whether the Pythagorean Theorem applies. For that you'll need to calculate the size of the three edges and then check whether A^2 + B^2 ~= C^2
Yes, there is.
x = [0,0.5,1]
y = [0,0.5,0]
points = [np.array(point) for point in zip(x,y)]
a, b, c = points
ba = a - b
bc = c - b
cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
angle_rad = np.arccos(cosine_angle)
angle_deg = np.rad2deg(angle_rad)
print(angle_deg) # 90.0
You can compute the angle between the two vectors as following: first, get the two vectors v1 and v2 and then use np.arccos() which returns the angle in radians. Convert it to degrees to check if it is 90 degrees. The formulae for computing angle between two vectors can be found on this Wiki link
import numpy as np
x = np.array([0,0.5,1])
y = np.array([0,0.5,0])
vecs = np.vstack((x, y))
v1 = vecs[:, 1] - vecs[:, 0]
v2 = vecs[:, 2] - vecs[:, 1]
angle_rad = np.arccos(np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
angle_deg = np.rad2deg(angle_rad)
# 90.0

Calculating area of a segment in a circle

You are given the diameter across, and the length of the segment or chord. The diameter for my question is 12, and the chord is 10. You have to find the height of the shaded segment, and then print the area. The original formula is A=2/3ch + h^3/2c. My classmates got 18 for the area, but when I use my code I get 41.
This is the closest picture representation I can find. However there is a dashed line from ϴ to s.
from math import sqrt
diamStr=input("Enter the length of the diameter: ")
diameter=int(diamStr)
chordStr = input( " Enter the chord length: ")
chord = int(chordStr)
radius = (diameter/2)
s = sqrt (diameter**2+chord**2)
h = (s/2-radius)
i= (2/3*chord*h)
j=(h**3/2*chord)
area = (i+j)
print (area)
Unfortunately there's something wrong with your formula but if look at the problem with some elementary mathematics you may notice that the angle ϴ can be found using the cosine rule since we know the 3 lengths (the two radius and chord length)
In Python it would be:
theta = math.acos((radius**2 + radius**2 - chord**2)/(2*radius**2))
Since the variable theta is already in radians we can use this formula to calculate the area of the segment :
which in python would be area = 1/2 * (theta - math.sin(theta)) * radius**2
Therefore after merging all of these we come up with a elegant solution:
import math
diamStr=input("Enter the length of the diameter: ")
diameter=int(diamStr)
chordStr = input( " Enter the chord length: ")
chord = int(chordStr)
radius = (diameter/2)
theta = math.acos((radius**2 + radius**2 - chord**2)/(2*radius**2))
area = 1/2 * (theta - math.sin(theta)) * radius**2
#print(round((area),2))
print(area)
If you enter diameter as 12cm and chord length as 10 you'll get 18.880864248381847 but you can round it to any number of decimal places you want by the round() function.
eg: print(round((area),2)) prints 18.88

Categories