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.
Related
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
I am trying to write a program that uses an array in further calculations. I initialize a grid of equally spaced points with NumPy and assign a value at each point as per the code snippet provided below. The function I am trying to describe with this array gives me a division by 0 error at x=y and it generally blows up around it. I know that the real part of said function is bounded by band_D/(2*math.pi)
at x=y and I tried manually assigning this value on the diagonal, but it seems that points around it are still ill-behaved and so I am not getting any right values. Is there a way to remedy this? This is how the function looks like with matplotlib
gamma=5
band_D=100
Dt=1e-3
x = np.arange(0,1/gamma,Dt)
y = np.arange(0,1/gamma,Dt)
xx,yy= np.meshgrid(x,y)
N=x.shape[0]
di = np.diag_indices(N)
time_fourier=(1j/2*math.pi)*(1-np.exp(1j*band_D*(xx-yy)))/(xx-yy)
time_fourier[di]=band_D/(2*math.pi)
You have a classic 0 / 0 problem. It's not really Numpy's job to figure out to apply De L'Hospital and solve this for you... I see, as other have commented, that you had the right idea with trying to set the limit value at the diagonal (where x approx y), but by the time you'd hit that line, the warning had already been emitted (just a warning, BTW, not an exception).
For a quick fix (but a bit of a fudge), in this case, you can try to add a small value to the difference:
xy = xx - yy + 1e-100
num = (1j / 2*np.pi) * (1 - np.exp(1j * band_D * xy))
time_fourier = num / xy
This also reveals that there is something wrong with your limit calculation... (time_fourier[0,0] approx 157.0796..., not 15.91549...).
and not band_D / (2*math.pi).
For a correct calculation:
def f(xy):
mask = xy != 0
limit = band_D * np.pi/2
return np.where(mask, np.divide((1j/2 * np.pi) * (1 - np.exp(1j * band_D * xy)), xy, where=mask), limit)
time_fourier = f(xx - yy)
You are dividing by x-y, that will definitely throw an error when x = y. The function being well behaved here means that the Taylor series doesn't diverge. But python doesn't know or care about that, it just calculates one step at a time until it reaches division by 0.
You had the right idea by defining a different function when x = y (ie, the mathematically true answer) but your way of applying it doesn't work because the correction is AFTER the division by 0, so it never gets read. This, however, should work
def make_time_fourier(x, y):
if np.isclose(x, y):
return band_D/(2*math.pi)
else:
return (1j/2*math.pi)*(1-np.exp(1j*band_D*(x-y)))/(x-y)
time_fourier = np.vectorize(make_time_fourier)(xx, yy)
print(time_fourier)
You can use np.divide with where option.
import math
gamma=5
band_D=100
Dt=1e-3
x = np.arange(0,1/gamma,Dt)
y = np.arange(0,1/gamma,Dt)
xx,yy = np.meshgrid(x,y)
N = x.shape[0]
di = np.diag_indices(N)
time_fourier = (1j / 2 * np.pi) * (1 - np.exp(1j * band_D * (xx - yy)))
time_fourier = np.divide(time_fourier,
(xx - yy),
where=(xx - yy) != 0)
time_fourier[di] = band_D / (2 * np.pi)
You can reformulate your function so that the division is inside the (numpy) sinc function, which handles it correctly.
To save typing I'll use D for band_D and use a variable
z = D*(xx-yy)/2
Then
T = (1j/2*pi)*(1-np.exp(1j*band_D*(xx-yy)))/(xx-yy)
= (2/D)*(1j/2*pi)*( 1 - cos( 2*z) - 1j*sin( 2*z))/z
= (1j/D*pi)* (2*sin(z)*sin(z) - 2j*sin(z)*cos(z))/z
= (2j/D*pi) * sin(z)/z * (sin(z) - 1j*cos(z))
= (2j/D*pi) * sinc( z/pi) * (sin(z) - 1j*cos(z))
numpy defines
sinc(x) to be sin(pi*x)/(pi*x)
I can't run python do you should chrck my calculations
The steps are
Substitute the definition of z and expand the complex exp
Apply the double angle formulae for sin and cos
Factor out sin(z)
Substitute the definition of sinc
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))
I have to write a function in which there is a square inscribed in a circle. The corners of the square touch the circle's perimeter.
The function call for find_area(4) should have a return value of 18.2400.
But I think the fact that I'm trying to incorporate a square root is messing with the code and not giving me any values.
Here is what I got so far:
import math
def find_area(r):
# area: area of circle - area of square
s = math.sqrt(2)
sidesquare = ( s * ((r*2) / 2)
square = ( sidesquare * 2)** 2
circle = (3.14 * r)** 2
area = circle - square
return (area)
if __name__ == '__main__':
print('Testing compute() with r = 4:' + str(find_area(4)))
There are few problems in your code, mainly you are using few unrequired parenthesis. Hope the below code should help you.
def find_area(r):
s = math.sqrt(2)
sidesquare = s * r * 2 / 2
square = (sidesquare * 2) ** 2
circle = 3.14 * r ** 2
area = circle - square
return area
If you crunch the math through by hand a bit more, you will find that the area of the square is 2 * r ** 2 and the circle is pi * r ** 2, so your function reduces to
from math import pi
def find_area(r):
return (pi - 2.) * r ** 2
or, if you insist on pi == 3.14,
find_area = lambda r: 1.14 * r ** 2
This is my code...it errors out on line 5 and I don't know why. Thanks for the help in advance.
The error is invalid syntax.
from math import pi
radius = int(raw_input(("What radius would you like?"))
def area_of_circle(radius):
return (radius ** 2) * math.pi
area_of_circle(radius)
Instead of
from math import pi
just use
import math
from math import pi loads the math module, but instead of assigning the module to the name math, it looks up pi in the module and assigns that to the name pi. This can be convenient, but it can also cause horrible initialization order issues.
I believe you're missing a closing parenthesis on line 2. But as Marius mentioned, you don't actually need those parentheses.
from math import pi
radius = int(raw_input("What radius would you like?")) # Parenthesis removed
def area_of_circle(radius):
return (radius ** 2) * math.pi
area_of_circle(radius)
On top of that, you should also look at the suggestion by #user2357112 and use import math and math.pi. The updated code will look like:
import math # Not import pi
radius = int(raw_input("What radius would you like?")) # Parenthesis removed
def area_of_circle(radius):
return (radius ** 2) * math.pi
# Printing here for feedback
print area_of_circle(radius)
it works fine
import math
radius = int(raw_input(("What radius would you like?")))
def area_of_circle(radius):
return (radius ** 2) * math.pi
print area_of_circle(radius)
you were missing ")" close parenthesis and the imported library should be math not pi.
import math
#parameter
radius = int(input("Enter the radius: "))
def AreaOfCircle(radius):
return (radius**2)*math.pi
print(AreaOfCirle(radius))