Archimedes PI Approximation in Python - python

Here is my code thus far,
from math import *
def main():
sides = eval(input("Enter the number of sides:"))
value = 360/(2 * sides)
sinvalue = sin(value)
PI = sinvalue * sides
print("Approximate value of pi =", PI)
However, I am not getting the proper value that is in the sample code.

math.sin expects angles to be specified in radians.
>>> print(math.sin.__doc__)
sin(x)
Return the sine of x (measured in radians).
You are specifying it in degrees. Specify the angle in radians instead:
value = math.pi / sides
Or, if you don't want to use math.pi so explicitly, use the helper function to convert units:
value = math.radians(360/(2*sides))

Related

How do I take radius as a float argument and return the area/volume of a sphere back as floats in python?

Why I have tried:
def sphere_area(radius: float):
area = float(4 * math.pi * radius * radius)
return area
def sphere_volume(radius: float):
volume = float((4 / 3) * math.pi * math.pow(radius, 3))
return volume
Expected output:
surface_area: #float number
volume: #float
If you want to output the area and volume of a sphere with a given radius, you need to call the functions you have defined.
For example, if you wanted the volume and surface area of a sphere with radius 2:
print(sphere_area(2))
print(sphere_volume(2))
We call the function name, put pass in our radius value, and print it out since we will only be returned a float value.
If you also wish, you can store the function values inside of two other variables:
sp_area = sphere_area(2)
sp_volume = sphere_area(2)
Remember to use import math at the top of your code so your code works when you use math functions.
I hope this helped! Let me know if you need any further clarifications or details :)

In python using while loop calculate circumference and area

Write a program that will calculate the circumference and surface area of a circle. Create a table that prints the circumference and surface area for a radius from 1cm to 20 cm inclusive in increments of .5 cm.
I've tried this
import math
def main():
# inputs
radius = int(20)
i = float
# loop
while i in range(1, radius+1):
a = math.pi * radius ** 2
c = 2 * math.pi * radius
print(f'{i:3d}{a:13.2f}{c:15.2f}')
break
main()
But nothing happens when I run the program.
You can initialize radius as 1 and loop until it is greater than 20, incrementing it by 0.5 at the end of each iteration.
def main():
radius = 1
while radius <= 20:
a = math.pi * radius ** 2
c = 2 * math.pi * radius
print(f'{a:13.2f}{c:15.2f}')
radius += .5
from numpy import pi
from numpy import arange
def main():
# Python makes it easy to directly loop over different radius values
# no need to manually check conditions (tip: have a look at iterators)
for radius in arange(0.5, 20.0, 0.5):
# directly assigns value to radius
# instead of the OPs checking of i in the while loop. No need for i at all
a = pi * radius**2
c = 2 * pi * radius
print(f'{radius}{a:13.2f}{c:15.2f}')
# no need for "break"
main() # call to function

How can I calculate tangent with degrees instead of radians?

I am trying to make a basic tool to make my everyday easier, solving some assignments for me. Unfortunately, I can't figure out how to make it calculate in degrees when tangent is being used.
My code:
import math
class Astro():
def start(self):
velocity = input("What is the galaxy's velocity? (m/s) \n")
peculiar = (float(velocity) - 938600) ** 2
mass = (3 * float(peculiar) * (10 ** 11) * 50 * (10 ** 6) * (8 * (180 / math.pi))
* 9.46 * (10 ** 15)) / (2 * 6.67 * (10 ** -11))
print("The galaxy's mass is " + str(mass) + " kg. \n")
if __name__ == '__main__':
sup = Astro()
sup.start()
EDIT: Sorry for the lack of context; this is about calculating the masses of galaxies using 2 functions, the first one, line 7 to get the peculiar velocity, and the second one in lines 8-9 to get the actual mass of the considered galaxy.
SOLVED: math.tan(8 * pi / 180)
Thank you for all your help!
Computers work in radians. Try
answer = tan(angle * pi / 180)
to use your angle in degrees into a trig function. Or try
answer = atan(number) * 180 / pi
to get answer in degrees.
The math package has the functions radians and degrees but under the hood these are just:
def radians(deg):
return deg * pi / 180
def degrees(rad):
return rad * 180 / pi
Here is a wrapper you can use to make degree-using trig functions (just had it lying around somewhere, although I use numpy instead of math)
import math
import itertools
import functools
def _use_deg(f, arc = False):
if not arc:
def df(*args):
args = list(args)
for index, value in enumerate(args):
try:
args[index] = math.radians(value)
except TypeError:
pass
return f(*args)
else:
def df(*args):
return math.degrees(f(*args))
return functools.wraps(f)(df)
sind = _use_deg(math.sin)
cosd = _use_deg(math.cos)
tand = _use_deg(math.tan)
arcsind = _use_deg(math.asin, True)
arccosd = _use_deg(math.acos, True)
arctand = _use_deg(math.atan, True)
arctan2d = _use_deg(math.atan2, True)
You don't want to get in a fight with the math library. Let the math library give you an answer in radians, then multiply it's answer by 180/math.pi to get degrees.

Python Work out area of a polygon on a spherical surface

I have a series of points, of right ascension and declination values.
These points correspond to the vertices of a polygon on the surface of a sphere.
What would be the best way to calculate the area enclosed by these points? I would assume that converting the points with an equal-area projection, and then carrying out typical polygonal area calculating on a flat surface would be an appropriate solution.
note: I cannot use custom python libraries. eg pyproj or shapely
Example code (works for latitude longitude, what modifications would be required to enure this works with sky coordinates?)
def reproject(latitude, longitude):
"""Returns the x & y coordinates in metres using a sinusoidal projection"""
from math import pi, cos, radians
earth_radius = 6371009
lat_dist = pi * earth_radius / 180.0
y = [lat * lat_dist for lat in latitude]
x = [long * lat_dist * cos(radians(lat))
for lat, long in zip(latitude, longitude)]
return x, y
def area_of_polygon(x, y):
"""Calculates the area of an arbitrary polygon given its vertices"""
area = 0.0
for i in xrange(-1, len(x)-1):
area += x[i] * (y[i+1] - y[i-1])
return abs(area) / 2.0
dec = [-15.,89.,89.,-15.,-15.]
ra = [105.,105.,285.,285.,105.]
x,y = reproject(dec, ra)
print area_of_polygon(x,y)
One of the ways is to perform a line integral based on Green's Theorem. See below an implementation, and this question for more details.
def polygon_area(lats, lons, algorithm = 0, radius = 6378137):
"""
Computes area of spherical polygon, assuming spherical Earth.
Returns result in ratio of the sphere's area if the radius is specified.
Otherwise, in the units of provided radius.
lats and lons are in degrees.
"""
from numpy import arctan2, cos, sin, sqrt, pi, power, append, diff, deg2rad
lats = np.deg2rad(lats)
lons = np.deg2rad(lons)
# Line integral based on Green's Theorem, assumes spherical Earth
#close polygon
if lats[0]!=lats[-1]:
lats = append(lats, lats[0])
lons = append(lons, lons[0])
#colatitudes relative to (0,0)
a = sin(lats/2)**2 + cos(lats)* sin(lons/2)**2
colat = 2*arctan2( sqrt(a), sqrt(1-a) )
#azimuths relative to (0,0)
az = arctan2(cos(lats) * sin(lons), sin(lats)) % (2*pi)
# Calculate diffs
# daz = diff(az) % (2*pi)
daz = diff(az)
daz = (daz + pi) % (2 * pi) - pi
deltas=diff(colat)/2
colat=colat[0:-1]+deltas
# Perform integral
integrands = (1-cos(colat)) * daz
# Integrate
area = abs(sum(integrands))/(4*pi)
area = min(area,1-area)
if radius is not None: #return in units of radius
return area * 4*pi*radius**2
else: #return in ratio of sphere total area
return area
Please find a somewhat more explicit version (and with many more references and TODOs...) here.
Looks like I can treat ra and dec like lat and long, work out the area on the Earth's surface in m^2, and use this value to convert into an area in sq degrees.
Please let me know if the solution I propose below is flawed:
def reproject(latitude, longitude):
"""Returns the x & y coordinates in metres using a sinusoidal projection"""
from math import pi, cos, radians
earth_radius = 6371009
lat_dist = pi * earth_radius / 180.0
y = [lat * lat_dist for lat in latitude]
x = [long * lat_dist * cos(radians(lat))
for lat, long in zip(latitude, longitude)]
return x, y
def area_of_polygon(x, y):
"""Calculates the area of an arbitrary polygon given its vertices"""
area = 0.0
for i in xrange(-1, len(x)-1):
area += x[i] * (y[i+1] - y[i-1])
return ((abs(area) / 2.0)/5.10100E14) * 41253
dec = [-15.,89.,89.,-15.,-15.]
ra = [105.,105.,285.,285.,105.]
x,y = reproject(dec, ra)
print area_of_polygon(x,y)

How do I write these equations in pure Python?

Given these example equations with all but the word degrees in broken python:
L = 280.460 degrees + 0.9856474 degrees * n
and
lamtha = L + 1.915 degrees * math.sin(g) + 0.020 degrees * math.sin(2*g)
How can I can I write these in functional python to get the correct values for L and lamtha?
math.sin requires that you pass radians to it when you call it. If you pass your input as degrees, you will not get the correct result - convert to radians before you call math.sin.
The return value of math.sin won't be in degrees or radians - it's just a ratio, so there's nothing to convert there.
It's necessary to convert all degrees where degrees are called for into into radians when operating on them or along with math.sin and similar functions that require radians as an argument. Finally, if I need to, I can convert the resulting lamtha into degrees with math.degrees.
L = math.radians(280.460) + math.radians(0.9856474) * n
g = math.radians(g)
lamtha = L + math.radians(1.915) * math.sin(g) + math.radians(0.020) * math.sin(2*g)

Categories

Resources