Trigonometry: sin(x) getting negative value - python

I am trying to solve a homework: I am required to write a program which will calculate the length of a ladder based on two inputs, that is the desired height to be reached and the angle created by leaning the ladder toward the wall.
I used the following formula to convert degrees to radians :
radians = (math.pi / 180) * x # x is the given angle by the user.
I imported the math library as well to use its functions.
def main():
import math
print("this program calculates the length of a ladder after you give the height and the angle")
h = eval(input("enter the height you want to reach using the ladder"))
x = eval(input("enter the angle which will be created be leaning the ladder to the wall"))
radians = ( math.pi / 180 ) * x
length = h / math.sin(x)
print("the length is:", length)
main()
What exactly am I doing wrong?
I know the code is missing something and would appreciate it if someone could help me fill the gap.

You never used radians after you calculate it.
i.e. length = h / math.sin(radians)

To make crickt_007's right answer absolutely clear: radians which you did not use after you calculate it should be the argument of the sine:
length = h / math.sin(radians)

you calculate radians,thats ok,but problem is you never used that radians value. i think your code must be changed as follows :)
def main():
import math
print("this program calculates the length of a ladder after you give the height and the angle")
h = eval(input("enter the height you want to reach using the ladder"))
x = eval(input("enter the angle which will be created be leaning the ladder to the wall"))
radians = ( math.pi / 180 ) * x
length = h / math.sin(radians)
print("the length is:", length)
main()
if your both input will be 5,output is the length is: 57.36856622834928

Related

Python degrees defaulting to radians

I'm trying to print out the x,y value for a line with a certain degree which intersects a circle with a specified radius.
Lets say for example that the line is pointing straight up at 90 degrees.
import math
degree = 90
radius = 10
x = radius * math.cos(degree)
y = radius * math.sin(degree)
print(x,y)
This prints out -4.480736161291701 8.939966636005579 but according to my calculator is supposed to print 0 10 on deg.
I have already tried adding math.radians and math.degrees before the degree var in the x = and y =, but it doesn't come out correctly any time I've tried. The link I found to the point where a line with degree intersects a circle is here, the sin/cos values are flipped 'tho for the x and y value in the solution.
Simply said, how would I make the 90 be in degrees instead of radians to get the correct x,y?
EDIT:
by adding math.radians:
x = radius * math.cos(math.radians(degree))
y = radius * math.sin(math.radians(degree))
it returned 6.123233995736766e-16 10.0
~~~
by adding math.degrees:
x = radius * math.cos(math.degrees(degree))
y = radius * math.sin(math.degrees(degree))
it returned -2.995153947555356 -9.540914674728182
In Python, you can use math.radians to convert from degrees to radians. Note that it is not just Python that defaults to radians, it is usually the standard in mathematics to talk about angles in radians.
Although, in general, you can always use the conversion formula
radians = pi * degrees / 180
You can use math.radians(degree) to convert to radians. All python's default trig functions work in radians. So your code becomes:
import math
degree = 90
radius = 10
x = radius * math.cos(math.radians(degree))
y = radius * math.sin(math.radians(degree))
print(x,y)
And this produces the correct result: 6.123233995736766e-16 10.0, with some odd floating point behavior you can fix with appropriate rounding.
All angles in most of the math libraries are in radians. The input to math.cos should be radians but you are passing in degrees.
import math
degree = 90
radius = 10
x = radius * math.cos(math.radians(degree))
y = radius * math.sin(math.radians(degree))
print x,y
>0, 10
math.radians is nothing more than doing (pi * degree / 180 )
If you're writing a somewhat longer code, you can make your code work in degrees by putting in the following lines in the beginning:
from math import sin, cos, tan, asin, acos, atan
def s(x):
return sin(rad(x))
def c(x):
return cos(rad(x))
def t(x):
return tan(rad(x))
def sa(x):
return deg(asin(x))
def ca(x):
return deg(acos(x))
def ta(x):
return deg(atan(x))
Then, throughout your code, instead of typing sin(90) you would type s(90), or for arcsin(90) you would type sa(90). (I couldn't make the code word as for arcsine, since as is already a Python word)
Now, you would just type up your code as though it were in degrees and everything should work out fine.

Calculate PI using Random Numbers

Having trouble with the following question:
In geometry the ratio of the circumference of a circle to its diameter is known as π. The value of π can be estimated from an infinite series of the form:
π / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
There is another novel approach to calculate π. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just π square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is π / 4.
To simuluate the throwing of darts we will use a random number generator. The Random module has several random number generating functions that can be used. For example, the function uniform(a, b) returns a floating point random number in the range a (inclusive) and b (exclusive).
Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.
A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. The way we achieve that is:
xPos = random.uniform (-1.0, 1.0)
yPos = random.uniform (-1.0, 1.0)
To determine if a point is inside the circle its distance from the center of the circle must be strictly less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is math.hypot (xPos, yPos). The radius of the circle is 1 unit.
The program that you will be writing will be called CalculatePI. It will have the following structure:
import math
import random
def computePI ( numThrows ):
...
def main ():
...
main()
Your function main() will call the function computePI() for a given number of throws. The function computePI() will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will determine if that randomly generated point is inside the circle or not. You will do this as many times as specified by the number of throws. You will keep a count of the number of times a dart lands within the circle. That count divided by the total number of throws is the ratio π/4. The function computePI() will then return the computed value of PI.
In your function main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by math.pi. The quantity Difference in the output is your calculated value of PI minus math.pi. Use the following number of throws to run your experiment - 100, 1000, 10,000, 100,000, 1,000,000, and 10,000,000. You will call the function computePI() with these numbers as input parameters. Your output will be similar to the following, i.e. the actual values of your Calculated PI and Difference will be different but close to the ones shown:
Computation of PI using Random Numbers
num = 100 Calculated PI = 3.320000 Difference = +0.178407
num = 1000 Calculated PI = 3.080000 Difference = -0.061593
num = 10000 Calculated PI = 3.120400 Difference = -0.021193
num = 100000 Calculated PI = 3.144720 Difference = +0.003127
num = 1000000 Calculated PI = 3.142588 Difference = +0.000995
num = 10000000 Calculated PI = 3.141796 Difference = +0.000204
Difference = Calculated PI - math.pi
Your output must be in the above format. The number of throws must be left justified. The calculated value of π and the difference must be expressed correct to six places of decimal. There should be plus or minus sign on the difference. Read the relevant sections in the book on formatting.
Till now I have done:
import math
import random
def computePI (numThrows):
xPos = random.uniform (-1.0, 1.0)
yPos = random.uniform (-1.0, 1.0)
in_circle = 0
throws = 0
while (throws < numThrows):
if math.hypot (xPos, yPos) <= 1:
in_circle += 1
throws += 1
pi = (4 * in_circle) / numThrows
return pi
def main ():
throws = (100, 1000, 10000, 100000, 1000000, 10000000)
for numThrows in throws[0:7]:
main ()
I am having trouble calling the ComputePI function in the Main function. Also how do I print num with left indentation and ensure that all numbers have the required decimal space? Thank you!
Your program has three main issues:
Generating random numbers in the wrong place
xPos = random.uniform (-1.0, 1.0)
yPos = random.uniform (-1.0, 1.0)
These lines are executed only once when you enter the computePI() function. You then proceed to calculate the exact same value of hypot for hundreds or even thousands of iterations. Put these lines inside the while loop.
Integer arithmetic
pi = (4 * in_circle) / numThrows
Since in_circle and numThrows are both integers, this calculation will be performed using integer arithmetic (in Python 2, at least). Changing the constant from 4 to 4.0 will change this to a floating point calculation:
pi = (4.0 * in_circle) / numThrows
Incomplete main() function:
There's no need to use a subset of your throws tuple, and you haven't added a body to your for loop. Try this:
for numThrows in (100, 1000, 10000, 100000, 1000000, 10000000):
randpi = computePI(numThrows)
diff = randpi - math.pi
print "num = %-8d Calculated PI = %8.6f Difference = %+9.6f" % \
(numThrows, randpi, diff)
This is how I find it easy.
import random
import math
def approximate_pi():
total_points = 0
within_circle = 0
for i in range (10000):
x = random.random()
y = random.random()
total_points += 1
distance = math.sqrt(x**2+y**2)
if distance < 1:
within_circle += 1
if total_points % 1000 == 0:
pi_estimate = 4 * within_circle / total_points
yield pi_estimate
set total point generated and points withing the circle to zero
total_points = 0
within_circle = 0
generate the random values of x and y for multiple times. Calculate the distance of the point from the center of the circle or (0,0). Then if the distance is less than one it means that it's within the circle so it is incremented.
distance = math.sqrt(x**2+y**2)
if distance < 1:
within_circle += 1
Now if you have generated let's say multiple of 1000(1000 because we have taken the range for 10,000 so 1000 to get 10 values of pi), calculate the estimated value of pi using this formula which you know already.and the tied the estimate value(pi_estmate)
if total_points % 1000 == 0:
pi_estimate = 4 * within_circle / total_points
yield pi_estimate
pi_estimates = list(es for es in approximate_pi())
errors = list(estimate-math.pi for estimate in approximate_pi())
print(pi_estimates)
print(errors)
OUTPUT:
Estimates
[3.096, 3.142, 3.1253333333333333, 3.121, 3.1384, 3.136, 3.1314285714285712, 3.133, 3.1342222222222222]
Errors
[0.04240734641020705, 0.02240734641020703, 0.03307401307687341, 0.020407346410206806, 0.02320734641020694, 0.0017406797435404187, -0.009021225018364554, -0.011592653589793223, -0.016703764700904067]
Hope you understood, I hope my explanation was easy to understand, I am a beginner and learning stuff if there is anything wrong please feel free to notify.
Thank you
Essentially what the statement you've written above says:
import math
def find_pi(iterations):
return sum(
1 for _ in range(iterations) if math.hypot(
random.random(), random.random()) <= 1) * 4.0/iterations

Random generator function in Python

I have been learning Java since September, but have been given an assignment for a science course by a professor to create a program in Python that will generate a random diameter using a max and minimum value, and 15 random points within this sphere (x, y, z).
I need to make a random number generator that generates a number between 0.0 and 1.0 so I can plug it into my formula to find a random diameter. If the random number is RN, it would be: [(RN*(max-min))+min]
At first I used this random function:
from random import*
RN=random():
The problem is, this random function is [0.0, 1.0). In other words, it does not include 1.0.
How can I create a function that includes 1.0?
Also, if you don't mind, can you help me with finding the y and z coordinates? I know how to find x.
The formula for the y value is y=+ or - sqrt(r^2-x^2) (to be randomly generated too).
I would have the x value, which is the result from the random function [0.0-1.0], and the radius which would be half my diameter. I am a complete beginner at Python, how do I initialize my x and y and put the above formula in?
The formula for z is similar, z=+ or - sqrt(-x^2-y^2+r^2) (to be randomly generated as well)
These are using the formulas for a circle:
radius: r=sqrt(x^2+y^2)
sphere:r=sqrt(x^2+y^2+z^2)
I would be incredibly grateful if you could answer any part of my question, thank you so much for taking the time to read this!!
**by the way, I am usinHi! I have been learning Java since September, but have been given an assignment for a science course by a professor to create a program in Python that will generate a random diameter using a max and minimum value, and 15 random points within this sphere (x, y, z).
I need to make a random number generator that generates a number between 0.0 and 1.0 so I can plug it into my formula to find a random diameter. If the random number is RN, it would be: [(RN*(max-min))+min]
At first I used this random function:
from random import*
RN=random():
The problem is, this random function is [0.0, 1.0). In other words, it does not include 1.0.
How can I create a function that includes 1.0?
Also, if you don't mind, can you help me with finding the y and z coordinates? I know how to find x.
The formula for the y value is y=+ or - sqrt(r^2-x^2) (to be randomly generated too).
I would have the x value, which is the result from the random function [0.0-1.0], and the radius which would be half my diameter. I am a complete beginner at Python, how do I initialize my x and y and put the above formula in?
The formula for z is similar, z=+ or - sqrt(-x^2-y^2+r^2) (to be randomly generated as well)
These are using the formulas for a circle:
radius: r=sqrt(x^2+y^2)
sphere:r=sqrt(x^2+y^2+z^2)
I would be incredibly grateful if you could answer any part of my question, thank you so much for taking the time to read this!!!
**by the way, I am using python x,y spyder!
random.uniform will give you a uniformly distributed random number between a given minimum and maximum.
Just generate random points and check if they are within the sphere. If they are not, discard them and try again.
import math
import random
def generate_points(n_points, min_diameter=0, max_diameter=1):
diameter = random.uniform(min_diameter, max_diameter)
radius = diameter / 2
count = 0
while count < n_points:
x, y, z = [random.uniform(-radius, radius) for _ in range(3)]
distance = math.sqrt(x * x + y * y + z * z)
if distance <= radius:
yield (x, y, z)
count += 1
for x, y, z in generate_points(10):
print x, y, z
Note: this may bias what points are generated. (I'm not sure, it's probably okay actually.) Another approach might be to use polar coordinates, choosing two random angles and a random radius (offset from center).
Here is the math for that approach:
theta = random.uniform(0, 2 * math.pi)
phi = random.uniform(-math.pi / 2, math.pi / 2)
x = r * cos(theta) * cos(phi)
y = r * sin(phi)
z = r * sin(theta) * cos(phi)
See here for more on distribution:
https://math.stackexchange.com/questions/87230/picking-random-points-in-the-volume-of-sphere-with-uniform-probability
http://mathworld.wolfram.com/SpherePointPicking.html (this one is about points on the surface of the sphere, so might not be as useful)
I used this for a random generator and it works, i'm not sure if it's the right one you're looking for but I hope it helps
import random
maths_operator_list=['+','-','*']
maths_operator = random.choice(maths_operator_list)
number_one = random.randint(0,20)
number_two = random.randint(0,20)
correct_answer = 0
print(str(number_one), str(maths_operator), number_two)
if maths_operator == '+':
correct_answer = number_one + number_two
elif maths_operator == '-':
correct_answer = number_one - number_two
elif maths_operator == '*':
correct_answer = number_one * number_two
print(correct_answer)
You can use random.range
random.randrange(-15,15,.1)
That will find a number between -15 and 15 that is divisible by 0.1.
As answer to the random number generator :
RN = random.uniform(a, b)
Return a random integer N such that a <= N <= b.
As how to initiate x and y, y will be initialize when you set y = to something, it does it automatically.

Python Drawing a Circle with X Radius Using Forward()

I'm using Python Turtles to draw a circle using forward() and right().
I have a for loop counting from 0 to 359, and each time it triggers, it moves the turtle forward 1 and right 1.
But the problem is I need specific diameters. I am nearly 100% sure I'll need to use trig, but I've tried to no avail.
I can't figure out the math how to do it. We're supposed to use forward() and right(), NOT circle().
Thanks!
Here is a working example:
import turtle
import math
def circle(radius):
turtle.up()
# go to (0, radius)
turtle.goto(0,radius)
turtle.down()
turtle.color("black")
# number of times the y axis has been crossed
times_crossed_y = 0
x_sign = 1.0
while times_crossed_y <= 1:
# move by 1/360 circumference
turtle.forward(2*math.pi*radius/360.0)
# rotate by one degree (there will be
# approx. 360 such rotations)
turtle.right(1.0)
# we use the copysign function to get the sign
# of turtle's x coordinate
x_sign_new = math.copysign(1, turtle.xcor())
if(x_sign_new != x_sign):
times_crossed_y += 1
x_sign = x_sign_new
return
circle(100)
print('finished')
turtle.done()
Well, a complete circle is 360°, and you are planning on turning 360 times, so each turn should be:
right( 360 ° / 360 ), or
right(1)
The distance traveled will be one circumference, or π * diameter, so your forward might be:
forward( diameter * π / 360 )
I haven't tested this yet -- give it a try and see how it works.
This is one of the exercises in "Think Python," in chapter 4. It really is a horrible exercise to have this early in the book, especially with the "hint" given. I'm using forward and left here, but you can switch left with right.
You should have the polygon function:
def polygon(t, length, n):
for i in range(n):
bob.fd(length)
bob.lt(360 / n)
Then you create a circle function:
def circle(t):
polygon(t, 1, 360)
That will draw a circle, no radius needed. The turtle goes forward 1, then left 1 (360 / 360), 360 times.
Then, if you want to make the circle bigger, you calculate the circumference of the circle. The hint says:
Hint: figure out the circumference of the circle and make sure that
length * n = circumference.
Ok, so the formula for circumference = 2 * pi * radius. And the hint says length * n = circumference. n = 360 (number of sides/degrees). We have circumference, so we need to solve for length.
So:
def circle(t, r):
circumference = 2 * 3.14 * r
length = circumference / 360
polygon(t, length, 360)
Now, call the function with whatever radius you want:
circle(bob, 200)

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