getting a repatted generated answer in python - python-3.x

I am trying to make a program which can help me on finding Area using Radius. but its output is very weird, take a look!
Pi = 3.1415929203539825
print('What is the Radius') #asking for Radius
R = input()
A = str(Pi) * int(R) * int(R)
print("The Area of this circle will be " + str(A) + "")
when R = 5, this is what it outputs:
3.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.1415929203539825

You don't need to cast pi to a string. Doing so repeats the string
Try this instead
from math import pi
R = float(input("enter a radius: "))
A = pi * (R**2)

Related

Chudnovsky algorithm python incorrect decimals

my goal is to get 100.000 or 200.000 correct decimals of Pi in Python. For this, I have tried using the Chudnovsky algorithm, but I've got some issues along the way.
First, the program only gives me 29 chars, instead of the 50 I want to test the correctness. I know this is a small issue, but I don't understand what I've done wrong.
Second, only the first 14 decimals are correct. After those, I start getting inaccurate Pi decimals according to about all Pi numbers on the internet. How do I get way more correct decimals?
And last, how do I let my code run on all 4 of the threads I have? I've tried using Pool, but it doesn't seem to work. (Checked it with Windows task manager)
This is my code:
from math import *
from decimal import Decimal, localcontext
from multiprocessing import Pool
import time
k = 0
s = 0
c = Decimal(426880*sqrt(10005))
if __name__ == '__main__':
start = time.time()
pi = 0
with localcontext() as ctx:
ctx.prec = 50
with Pool(None) as pool:
for k in range(0,500):
m = Decimal((factorial(6 * k)) / (factorial(3 * k) * Decimal((factorial(k) ** 3))))
l = Decimal((545140134 * k) + 13591409)
x = Decimal((-262537412640768000) ** k)
subPi = Decimal(((m*l)/x))
s = s + subPi
print(c*(s**-1))
print(time.time() - start)
In addition to the small details discussed in the comments and proposed by #mark-dickinson I think I've fixed the multithreading but I haven't had a chance to test it, let me know if it works properly
UPDATE: Problems after the 28th digits were due to the assignment of sq and c before the decimal context change. Reassign their value after changing the context precision solved the problem
from math import *
import decimal
from decimal import Decimal, localcontext
from multiprocessing import Pool
import time
k = 0
s = 0
sq = Decimal(10005).sqrt() #useless here
c = Decimal(426880*sq) #useless here
def calculate():
global s, k
for k in range(0,500):
m = Decimal((factorial(6 * k)) / (factorial(3 * k) * Decimal((factorial(k) ** 3))))
l = Decimal((545140134 * k) + 13591409)
x = Decimal((-262537412640768000) ** k)
subPi = Decimal((m*l)/x)
s = s + subPi
print(c*(s**-1))
if __name__ == '__main__':
start = time.time()
pi = 0
decimal.getcontext().prec = 100 #change the precision to increse the result digits
sq = Decimal(10005).sqrt()
c = Decimal(426880*sq)
pool = Pool()
result = pool.apply_async(calculate)
result.get()
print(time.time() - start)

How to pick 1 of my 3 formulas in my program?

I just wrote up a program to ask the user to calculate the area, circumference, and the diameter of a circle based on a radius input. However, I'm stumped on how to ask which calculation they want to make between the 3 choices. which is step 1. I have completed 2-4 steps. Any help on this one? (I.e. Only allow them to make one calculation per run of the program) The bolded area is obviously what I tried and failed miserably at....
**Radius = float(input("What type of calculation would you like to
make? "))
if 1 = "area"
elif: 2 = "circumference"
else: 3 = "diameter"
return("num")**
PI = 3.14
radius = float(input(' Please Enter the radius of a circle: '))
area = PI * radius * radius
circumference = 2 * PI * radius
print(" Area Of a Circle = %.2f" %area)
print(" Circumference Of a Circle = %.2f" %circumference)
import math
circumference = float(input(' Please Enter the Circumference of a
circle: '))
area = (circumference * circumference)/(4 * math.pi)
print(" Area Of a Circle = %.2f" %area)
import math
diameter = float(input(' Please Enter the Diameter of a circle: '))
area1 = (math.pi/4) * (diameter * diameter)
# diameter = 2 * radius
# radius = diameter/2
radius = diameter / 2
area2 = math.pi * radius * radius
print(" Area of Circle using direct formula = %.2f" %area1);
print(" Area of Circle Using Method 2 = %.2f" %area2)
As per your requirement that to get calculate area, circumference and diameter of circle based on radius input and to make one calculation per one run with choice selected.
I have made a sample/example code for you!
import math
def CalculateArea(radius):
# r = float(input('Enter the radius of the circle :'))
area = math.pi * radius * radius
return area
def CalculateCircumference(radius):
circ = 2 * math.pi * radius
return circ
def DiameterOfCircle(radius):
return radius * 2
radius = input('Enter Radius: ')
radius = float(radius)
choice = input(" Enter 1 to get Area \n Enter 2 for Circumference \n Enter 3 for Diameter! \n")
if choice is '1':
print("Area of the circle is : %.2f" % CalculateArea(radius))
elif choice is '2':
print("Circumference of circle is: ", CalculateCircumference(radius))
elif choice is '3':
print("Diameter of circle is: ", DiameterOfCircle(radius))
else:
print("Wrong Input!")
I hope this helps you! :)

ValueError: operands could not be broadcast together with shapes (3,) (0,)

My aim is to make the image1 move along the ring from its current position upto 180 degree. I have been trying to do different things but nothing seem to work. My final aim is to move both the images along the ring in different directions and finally merge them to and make them disappear.I keep getting the error above.Can you please help? Also can you tell how I can go about this problem?
from visual import *
import numpy as np
x = 3
y = 0
z = 0
i = pi/3
c = 0.120239 # A.U/minute
r = 1
for theta in arange(0, 2*pi, 0.1): #range of theta values; 0 to
xunit = r * sin(theta)*cos(i) +x
yunit = r * sin(theta)*sin(i) +y
zunit = r*cos(theta) +z
ring = curve( color = color.white ) #creates a curve
for theta in arange(0, 2*pi, 0.01):
ring.append( pos=(sin(theta)*cos(i) +x,sin(theta)*sin(i) +y,cos(theta) +z) )
image1=sphere(pos=(2.5,-0.866,0),radius=0.02, color=color.yellow)
image2=sphere(pos=(2.5,-0.866,0),radius=0.02, color=color.yellow)
earth=sphere(pos=(-3,0,-0.4),color=color.yellow, radius =0.3,material=materials.earth) #creates the observer
d_c_p = pow((x-xunit)**2 + (y-yunit)**2 + (z-zunit)**2,0.5) #calculates the distance between the center and points on ring
d_n_p = abs(yunit + 0.4998112152755791) #calculates the distance to the nearest point
t1 = ( d_c_p+d_n_p)/c
t0=d_c_p/c
t=t1-t0 #calculates the time it takes from one point to another
theta = []
t = []
dtheta = np.diff(theta) #calculates the difference in theta
dt = np.diff(t) #calculates the difference in t
speed = r*dtheta/dt #hence this calculates the speed
deltat = 0.005
t2=0
while True:
rate(5)
image2.pos = image2.pos + speed*deltat #increments the position of the image1
t2 = t2 + deltat
Your problem is that image2.pos is a vector (that's the "3" in the error message) but speed*deltat is a scalar (that's the "0" in the error message). You can't add a vector and a scalar. Instead of a scalar "speed" you need a vector velocity. There seem to be some errors in indentation in the program you posted, so there is some possibility I've misinterpreted what you're trying to do.
For VPython questions it's better to post to the VPython forum, where there are many more VPython users who will see your question than if you post to stackoverflow:
https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users

Installing and running vpython with Python 3.5 on Windows 10

I'm trying to install vpython with python3.5 on windows 10.
I used the following commands in the cmd:
pip install vpython
pip install update --ipython
If I then try to run some vpython code (copied from internet to simulate projectile motion):
from vpython import *
from math import sin, cos
initialHeight = 4.6
initialVelocity = 24
Angle = 65
#Set up the display window
scene1 = display(title = "Projectile Motion for the uninitiated",
x=0,y=0, width=800, height=600,
range=10, background=colour.white,
center = (10,initialHeight,0))
#Create objects
table = box(pos=(-1,initialHeight - 1,0), size=(5,1,4))
ball1 = sphere(pos=(0,initialHeight,0),radius=1,
color=color.green, make_trail = true)
ball2 = sphere(pos=(0,initialHeight,0),radius=1,
color=color.red, make_trail = true)
floor = box(pos=(0,0,0), size =(100,0.25,10))
t=0
dt=0.01
g=-32 #ft/s**2
Fgrav = vector(0,g*dt,0)
#velocity vector for ball1
ball1v = vector(initialVelocity*cos(Angle*pi/180),
initialVelocity*sin(Angle*pi/180),0)
#This loop puts it into motion
while True:
rate(30) #speeds it up
ball1v = ballv + Fgrav
ball1.pos += ball1.v*dt
ball2.pos = (initialVelocity*cos(Angle*pi/180)*t,
initialHeight + initialVelocity*t*sin(Angle*pi/180) - 16*t**2)
if ball1.y < 0: #when ball hits floor
print("ball1.pos = ", ball1.pos, "t = ", t)
print("ball2.pos = ", ball2.pos, "t = ", t)
break
When I run this I then get the following errors:
Traceback (most recent call last):
File "C:/Users/yours_truly/Google Drive/Python/projectile motion.py", line 1, in <module>
from vpython import *
File "C:\Users\yours_truly\AppData\Local\Programs\Python\Python35-32\lib\site-packages\vpython\__init__.py", line 10, in <module>
from .vpython import *
File "C:\Users\yours_truly\AppData\Local\Programs\Python\Python35-32\lib\site-packages\vpython\vpython.py", line 442, in <module>
get_ipython().kernel.comm_manager.register_target('glow', GlowWidget)
AttributeError: 'NoneType' object has no attribute 'kernel'
I cannot understand the problem here, nor can I make sense of the discussions of this that I have found online. Can anyone tell me what the score is here? Is vpython incompatible with python 3.5 (which I've read in some places) or is there a workaround (which I've also read in other places)?
Thank you.
I cannot remember when exactly support for Python 3.5 became available; it is certainly supported now. But the problem may have been associated with the fact that the program has a number of errors. Here is a version that works, including with Python 3.5 on Windows 10. The corrections were to change true -> True, bal
from vpython import *
from math import sin, cos
initialHeight = 4.6
initialVelocity = 24
Angle = 65
#Set up the display window
scene1 = display(title = "Projectile Motion for the uninitiated",
x=0,y=0, width=800, height=600,
range=10, background=color.white,
center = (10,initialHeight,0))
#Create objects
table = box(pos=vec(-1,initialHeight - 1,0), size=vec(5,1,4))
ball1 = sphere(pos=vec(0,initialHeight,0),radius=1,
color=color.green, make_trail = True)
ball2 = sphere(pos=vec(0,initialHeight,0),radius=1,
color=color.red, make_trail = True)
floor = box(pos=vec(0,0,0), size =vec(100,0.25,10))
t=0
dt=0.01
g=-32 #ft/s**2
Fgrav = vector(0,g*dt,0)
#velocity vector for ball1
ball1v = vector(initialVelocity*cos(Angle*pi/180),
initialVelocity*sin(Angle*pi/180),0)
#This loop puts it into motion
while True:
rate(30) #speeds it up
ball1v = ball1v + Fgrav
ball1.pos += ball1v*dt
ball2.pos = vec(initialVelocity*cos(Angle*pi/180)*t,
initialHeight + initialVelocity*t*sin(Angle*pi/180) - 16*t**2,0)
if ball1.pos.y < 0: #when ball hits floor
print("ball1.pos = ", ball1.pos, "t = ", t)
print("ball2.pos = ", ball2.pos, "t = ", t)
break

Printing a hollow circle using asterisks (so no turtle)

For a school assignment I need to print a smiley using a hollow circle.
def circle(i):
i += 1
from math import sqrt
result = ""
midden = i / 2.0
for a in range(i):
for b in range(i):
c = sqrt((midden - a)**2 + (midden - b)**2)
if midden > c:
result += "#"
else:
result += " "
result += "\n"
print(result)
circle(11)
The code above is what I have used to print a filled circle but i cannot for the life of me figure out how to make the circle hollow
Here is code that will first create a matrix with spaces, and walks along 1/8th of the circle, placing '#' characters. The 7 mirroring positions can be set at the same time, filling the complete circle. Finally the matrix is converted to a string which is returned.
from math import sqrt
def circle(radius):
pixels = [[' ' for x in range(2*radius+1)] for y in range(2*radius+1)]
y = radius
x = 0
max = (radius + 0.5)**2
while x <= y:
pixels[radius+y][radius+x] = '#'
pixels[radius+y][radius-x] = '#'
pixels[radius-y][radius+x] = '#'
pixels[radius-y][radius-x] = '#'
pixels[radius+x][radius+y] = '#'
pixels[radius+x][radius-y] = '#'
pixels[radius-x][radius+y] = '#'
pixels[radius-x][radius-y] = '#'
x += 1
if x*x + y*y >= max:
y -= 1
return '\n'.join([''.join([v for v in row]) for row in pixels])
print(circle(11))

Resources