Basic troubles with python maths - python

Working on a very simple program to learn python.
The goal is to calculate Euler's constant with the user inputing a value for the equations precision (p). The program should use that variable in the equation (1+1/p)^(10^p).
I am currently having two problems with this program. The first of which is that the program will work if I first define p as p=10**p, then use the equation (1+1/p)**p which brings us to the second problem.
The second problem is that any (user inputted) value for p that exceeds 14 will not work at all. (15 returns 3.035035... and higher values just return 1.0)
I am extremely new to python and its math syntax and that may be my problem.
Thank you all for any help
Code in question:
import math
p=None
e=None
p = int(input('Please enter a whole number precison multiplier (1-14):'))
p=10.0**p
print((1.0+1.0/p)**p)

I guess you're trying to approximate e. The formula is (1 + 1/p)^p as p -> infinity, not (1 + 1/p)^(10^p). This should work:
p = int(input('Please enter a whole number precison multiplier:'))
print((1 + 1/p)**(p))

Related

My Dynamic Programming program is surprisingly adding numbers instead of solution

In the book "Introduction to Algorithms", I am trying to implement a Dynamic Programming problem which is known as "rod-cutting-program". Here I have an array defining the price of rods of variable lengths. So, array {1, 4} defines that, price of a rod with length 1 inch is 1$, and the price of a rod with length 4 is 4$ as well. I am given an input which is a length of a given rod. My goal is to cut the rod into multiple pieces so that the length of each piece remains integer and the total price of the pieces is maximized.
Here is my program
print("Input Length Prices: ")
p = [int(x) for x in input().split()]
def cut_rod(n):
if n == 0:
return 0
q = -1
for i in range(1, n+1):
q = max(q, p[i-1] + cut_rod(n-1))
return q
print("Input Length to Cut: ")
print(cut_rod(int(input())))
Here are my Input and Output.
Input
1 4
2
Output
5 (This is the sum of 1 and 4)
Expected Output
4
So instead of the maximized total price, it is giving the sum of all prices of lengths. I have tried several other inputs too. In all cases, it is giving the sum. It's very strange.
Edit: Rod can be kept uncut too.
There are two problems with your program:
#1) You need cut_rod(n-i) rather than cut_rod(n-1) in your recursive call. Once you remove a piece of length i, you have p-i remaining.
#2) You are repeatedly calling cut_rod recursively, and for large values of n, you are making O(n*n) recursive calls . The point of dynamic programming is that you calculate the value for smaller results, and then cache them rather than recalculate them every time you need them.
Fortunately, Python makes this easy. Just annotate your code with #functools.lru_cache(None)
=== Correction ===
I wrote above that this code without cacheing was O(n*n). This is actually exponential or worse. The naive recursive implementation of Fibonacci numbers is exponential, and that only makes two recursive calls for each argument n greater than 2; this program makes n - 1.

Creating Catalan number loop and graphing it [python]

Let me preface it with that I am new to python completely and programming for that matter and I need to create a program to print all Catalan numbers up to one trillion. I have the basics of the program written out but I can't seem to understand why I'm not getting the right numbers. Also I am running into programs when trying to graph the trend out. Thanks in advance and here is the code I have:
import numpy as np
import scipy as sp
from pylab import *
def Catalan(n):
if n==0:
return (1)
elif n==1:
return (1)
else:
return ((4*n+2)/(n+2))*Catalan(n-1)
for n in range(18):
print (Catalan(n))
n=np.linspace(0,18,100)
y=Catalan(n)
plot(n,y,'r')
show()
There are two main mistakes in your Catalan function.
First, as seen in http://en.wikipedia.org/wiki/Catalan_number, the formula you wrote is useful to compute Catalan(n+1) in terms of Catalan(n). To use it to compute Catalan(n) in terms of Catalan(n-1), as you do, you must shift the index. So it should be (4*n-2)/(n+1)*Catalan(n-1).
Second, python uses integer arithmetic when dealing with ints. So, the quotients get rounded down to ints (this is, 5/2 gives 2, not 2.5). One way to deal with this is to write first the product and then the quotient: (4*n-2)*Catalan(n-1)/(n+1).
Nevermind programming, your formula looks broken. Take n=2:
return ((4*n+2)/(n+2))*Catalan(n-1)
= ((4*2+2)/(2+2))*Catalan(2-1)
= (( 8 +2)/( 4 ))*Catalan( 1 )
= (( 10 )/ 4 )* 1
= 2.5

Computing the circumference, area, and ratio of circumference to area of a circle

Studying for a CS test and basically I have to follow instructions that are similar to this.
Write a program, that is a file containing a main function followed by
a call to the main, and name the program ratio.py. The basic structure
of the program should look like this:
def main():
...
return
main() where the ellipsis indicates where you should place the code that performs following computations:
-you should prompt the user for an integer value corresponding to the
radius of a circle. Do this with code similar to:
radius = int(input("circle radius? "))
compute the circumference of the circle using the formula c = 2 πr where r is the radius and c is the circumference. Use the value of
3.14159 for π
compute the area of the circle using the formula c = πr2
print the ratio of the circumference to the area (the ratio of a to b is a divided by b)
Here is what I have written so far. I got the circumference and the area but how do I get it to make a ratio between the two and print the ratio.
def main():
radius = int(input("circle radius? "))
pi = 3.14159
r = radius
c = 2*pi*r
print(2*pi*r)
a = pi*r*r
print(pi*r*r)
ratio = c / a
return(ratio)
print("the ratio of the circumference to the area is",ratio)
main()
The ultimate goal is to get something like this:
$ python3 ratio.py
circle radius? 2
the ratio of the circumference to the area is ????
where ???? is replaced by the actual ratio.
You are extremely close to solving this. Here are a couple ideas to help you finish it:
import statements should generally go at the top of the file, not inside a function. They will work in the function, but it is poor form. This was probably not taught in class, but you get used to seeing particular patterns as you read other people's code.
As a matter of style, Python generally uses capital letters for names of constants, so PI=3.14159 is more common than pi=3.14159. This is minor and works either way. It is a good style to adhere to, since it will help make your code match others' code.
You need to calculate the area using the equation given to you: a = PI*r*r (NOTE - the original question incorrectly uses 'c' for the area. 'c' is the circumference.)
You need to return c/a, which is the ratio that was requested.
You probably need to print out the return value for testing. You can do that by storing the value returned by main() in a variable and then printing it.
Here is how to return a value from your main() function:
def main():
...
return c/a
ratio = main()
print(ratio)
# or...
print("The ratio is:", ratio)
it's odd that you do c = (2*math.pi*r) when you have pi declared as a variable above two lines. Doing math.pi goes to python's math library and digs up a more accurate version of pi. For all intents and purposes, you are just completely not using that pi variable.
see http://docs.python.org/2/library/math.html for more information.
Furthermore, you do the same computation twice.
c = 2*math.pi*r
return(2*math.pi*r)
c just ends up being garbage collected (which is to say, the computer does the computation then INTO THE TRASH IT GOES) and never being used. It would be better to simply return c
For scoping issues, which I'm sure you wouldn't really know about as a beginner, put import math above your main function, unindented.
just for future reference though, SO tends to be for isolated problems that you have spotted in code; not for a full code review. A more acceptable question would be along the lines of "my function is returning an unexpected value", not "my function is not working"

Time - Gravity Fall program

I am trying to create a program that will work out how long it will take for something to hit the ground when dropped from a particular height and it uses the known quadratic formula. The program appears to be doing what I want of it until it reaches line 7 where there is a math issue I beleive involving sqrt. Can anybody help?
So far I have come up with...
v = float(input())
lowerSum = 2*(-4.9)
upperSum1 = -4*(-4.9)
upperSum2 = (upperSum1)*(11000)
upperSum3 = (v)**2 - (upperSum2)
from math import sqrt
upperSum4 = (v) - sqrt(upperSum3)
t = (upperSum4) / (lowerSum)
print (t)
When I run the program it states that there is a math domain error; I'm new to programming and I do not know what this means.
I am trying to print out the value of t.
You misread the formula (bottom of page).
Specifically, you are applying the minus sign after v**2 twice:
First you apply it here (incorrectly, as if it was a negative sign):
upperSum1 = -4*(-4.9)
Then you apply it again here (correctly, as a minus symbol).
upperSum3 = (v)**2 - (upperSum2)
upperSum1 should be:
upperSum1 = 4*(-4.9)
The 'math domain error' is telling you that you've passed the sqrt function a value that is outside it's "domain". The domain of the sqrt function is the positive numbers. At some point upperSum3 becomes negative, which makes the sqrt rather unhappy, so it throws an error at you.
You could fix this by adding an if statement to change what your code does if upperSum3 is less than 0, for example:
if upperSum3 < 0:
#do something other than take the sqrt
else:
upperSum4 = (v) - sqrt(upperSum3)
Just going a bit deeper into the problem by doing the math...
v = float(input())
lowerSum = -9.8
upperSum1 = 19.6
upperSum2 = 215600
upperSum3 = (v)**2 - (215600)
from math import sqrt
upperSum4 = (v) - sqrt(upperSum3)
t = (upperSum4) / (lowerSum)
print (t)
So you have to have the square of v in line 5 be more than 215600 for the equation to not return a negative number to sqrt(), which is what is causing the error.
V has to be greater than 465 for the upperSum3 to be positive, and by running various numbers, it never actually becomes positive, so there's definitely something wrong with the equation you are using, or the set-up itself.
Without knowing the formula myself (which I can't find) there's no way for me to tell which part of the code is actually wrong.
import math
v=float(input())
t=float()
Result1=float(v-(math.sqrt(float(v**2)-float(4*(-4.9))*(11000))))
Result2=float(2*(-4.9))
t=float(Result1/Result2)
print(t)
This works. However, I'm new to python and was having trouble with my results converting to an integer. So.... if my use of "float" seems excessive, it's cause it is :-) For a good half an hour I was trying to perform all of the calculations on one line but gave up and broken it down. If anyone has a better solution that performs the calculation on one line I'm all ears.

writing an improved version of the Chaos Help

Here is the question proposed by the text.
Write an improved version of the Chaos program from Chapter 1 that allows a user to input two initial values and the number of iterations and then prints a nicely formatted table showing how the values change over time. for example, if the starting values were .25 and .26 with 10 iterations, the table would look like so:
following this is a table with a index 0.25 0.26 as headers and then the 10 iterations in two columns.
here is my initial Chaos program.
# File: chaos.py
def main ():
print ("This program illustrates a chaotic function")
x=eval (input("enter a number between 0 and 1: "))
for i in range (10):
x = 3.9 * x * (1-x)
print (x)
main()
my question is how do i change it to fulfil the above question..
Please if answering take in mind this is my first programming class ever.
You really just have to duplicate the functionality you already have. Instead of just asking the user for an x value, also ask for a y value.
x= float(input("enter a number between 0 and 1: "))
y= float(input("enter another number between 0 and 1: "))
Then in your loop you need to do the same thing you did with the x value to the y value. When you print, remember that you can print two values (x and y) at once by separating them with a comma.
Also, as PiotrLegnica said, you should use float(input(...)) instead of eval(input(...)). Since you know that the user should enter a floating point number (between 0 and 1) you don't have to call eval. Calling eval could be dangerous as it will execute any instruction given to it. That might not matter right now, but it's better to not get in the habit of using it.

Categories