In python using while loop calculate circumference and area - python

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

Related

Trying to figure out how to find the final distance on my turtle with random number

This is my code, I'm trying to figure out how to get the total distance of the entire length that my turtle has traveled and I don't know how to figure it without taking it out of a loop which I can't do because the numsteps is an input. This is for school by the way
for a in range(numsteps):
s = randint(-100,100)
angle = random() * 2 * pi
x = s * cos(angle)
y = s * sin(angle)
walking.goto(x,y)
distance = sqrt(x ** 2 + y ** 2)
finald.goto(x,y)
print("The final distance is {:,.0f}".format(distance))
print("Your total distance traveled is {}")
You have to save your previous position to compute the distance from the current position to it.
Then every time after computing the distance (near the end of the loop) the current position becomes a previous one:
from math import sin, cos, pi, sqrt
from random import random, randint
start_x, start_y = 0, 0 # The starting point coordinates
previous_x, previous_y = start_x, start_y
total_distance = 0 # We will progressively increase it
numsteps = int(input("Number of steps: "))
for __ in range(numsteps):
s = randint(-100, 100)
angle = random() * 2 * pi
x = s * cos(angle)
y = s * sin(angle)
# walking.goto(x, y) # I commented it out for testing
distance = sqrt((x - previous_x) ** 2 + (y - previous_y) ** 2)
total_distance += distance
prev_x, prev_y = x, y
final_distance = sqrt((x - start_x) ** 2 + (y - start_y) ** 2)
print("The final distance is {:,.0f}".format(final_distance))
print("Your total distance traveled is {:,.0f}".format(total_distance))
Note the __ instead of your a (or other regular name) — this special name (one or two underscore characters) indicates that its value is out of our interest.
(Because we use range(numsteps) only as a counter.)
I'd make simplifications based on some observations:
Turtle already knows the distance function, no need to reinvent it
Moving backwards (negative distance) when we can head in any direction is redundant -- it's really no different than moving forward in any direction.
We can more easily calculate how far we did move than measure how far we will move.
This results in code more like:
from math import pi
from random import random
from turtle import Screen, Turtle
numsteps = int(input("Number of steps: "))
screen = Screen()
walking = Turtle()
walking.radians()
total_distance = 0 # sum of all distances traveled
for _ in range(numsteps):
previous = walking.position()
angle = random() * 2 * pi
distance = random() * 100
walking.setheading(angle)
walking.forward(distance)
total_distance += walking.distance(previous)
final_distance = walking.distance(0, 0) # distance from where we started
print("Your final distance traveled is {:,.0f} pixels".format(final_distance))
print("Your total distance traveled is {:,.0f} pixels".format(total_distance))
screen.exitonclick()
OUTPUT
> python3 test.py
Number of steps: 100
Your final distance traveled is 356 pixels
Your total distance traveled is 4,630 pixels
>

using while loop in python to find volume and surface area of a cone but getting incorrect answers except the first radius entered

I am trying to find the volume and surface area of a cone using the radius from 10-20 with a step of .5 and print the results. I get the correct response when using 10 but all the following responses are wrong. What am I missing?
Here's what I've got:
pi = 3.14159265359
radius = 10
height = radius * 2
import math
print ('{0: <10}'.format('radius'),\
'{0: <10}'.format('area'),\
'{0: <10}'.format('volume'))
while radius >= 9.5 and radius <= 20:
area = pi * radius * (radius + math.sqrt(height**2 + radius**2))
volume = pi * radius**2 * height / 3
print(format(radius, '<10,.2f'), \
format(area, '<10,.2f'), \
format(volume, '<12,.2f'))
radius = radius + .5
You should add height = radius * 2 after the last line. Remember about the indentation.

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.

How to make a square inscribed in a circle?

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

Show how a projectile (turtle) travels over time

I am new to Python, and currently having a rough time with turtle graphics. This is what I am trying to solve
On Turtellini (the planet where Python turtles live) the
transportation system propels turtles with a giant slingshot. A
particular turtle's original location (x0, y0) is (-180, -100). He is
then shot upward at an initial vertical velocity (vy) of 88 units per
second and a horizontal velocity (vx) of 20 units per second to the
right. He travels for 16 seconds. The acceleration due to gravity (g)
is 11 units per second squared. The the location of the turtle at a
given second (t) is calculated as follows: x = x0 + vx * t and y = y0
+ vy * t - g/2 * t2 . This program is to show how a turtle travels over this period of time.
The output should be like this:
Here is what I should do;
set up the constants (vertical velocity, horizontal velocity,
gravity) and variables (x and y coordinates) set up the turtle by
giving him a proper shape, putting his tail up, moving him to the
initial position, putting his tail down make a loop that repeats for
seconds 1 through 16 inclusive. in each iteration of the loop display
the the values of the x and y variables (in the shell window), move
the turtle to those coordinates, have the turtle stamp his shape,
calculate the new values for the x and y variables after the loop
terminates, move the turtle to the last calculated coordinates,
change his color, and stamp his shape, then wait for a mouse click
My code so far:
import turtle
def main():
wn = turtle.Screen()
turtellini = turtle.Turtle()
t = int(input("Blab blab blab: "))
x0 = -180
y0 = -100
vx = 20
vy = 88
g = 11
x = (float(x0 + vx * t))
y = (float(y0 + vy * t - g / 2 * t**2))
turtellini.color("black")
turtellini.shape("turtle")
turtellini.up()
turtellini.goto(-180,-100)
turtellini.down()
for i in range(1,16,1):
turtellini.stamp()
turtellini.forward(i)
turtellini.right(i)
print(x)
print(y)
if __name__ == "__main__":
main()
I know I am doing bad; but can anyone help me to solve this problem?
You seem to have most of the parts and pieces. The biggest issue I see is you didn't put your x,y calculation in the loop. The loop iteration variable i is really t in your motion equations. Each time you calculate a new x,y you simply move the turtle to that position:
import turtle
from math import pi, atan
x0, y0 = -180, -100 # initial location
vx, vy = 20.0, 88.0 # initial velocity in units per second
travel_time = 16 # seconds
g = 11.0 # acceleration due to gravity in units per second squared
turtellini = turtle.Turtle(shape='turtle', visible=False)
turtellini.penup()
turtellini.radians() # to make turtle compatible with math.atan()
turtellini.setheading(pi / 2) # straight up
turtellini.goto(x0, y0)
turtellini.pendown()
turtellini.showturtle()
turtellini.stamp()
for t in range(1, travel_time + 1):
x = x0 + vx * t
y = y0 + vy * t - g / 2 * t**2
turtellini.goto(x, y)
print(x, y)
angle = atan((vy * t - g * t**2) / (vx * t)) # a guess!
turtellini.setheading(angle)
turtellini.stamp()
turtle.exitonclick()
Unlike the gold standard image, I assumed the turtle was aerodynamic like a bullet and travelled head first through the flight. I don't know, and couldn't quickly find, the formula for the flight angle of a projectile so I guessed from the existing formulas:

Categories

Resources