closest output to euler python - python

how to find which formula is closer to euler
import math
n = abs(int(input("enter a number: ")))
e = math.e
first = (1+ 1/n)**n
second = (1- 1/n)**n
if second == 1/e or second < 1/e:
print("second is closest to e")
elif first == e or first < e:
print("first is closest to e")
else:
print("tie")
without programming
first = e = (1+1/n)^n
first = 2.7048138294215285
second = 1/e = (1 - 1/n)^n
second = 2.7319990264290284
so first is closer to Euler but my output always is give me second why?
forgot to mention n is 100

That is because your checks are not right. second is 0.3660323412732292 and 1/e is 0.36787944117144233, so second < 1/e is in fact True but that doesn't mean that second is closer to e than first. Instead, you should compare actual distances:
dist_first = (first - e) ** 2
dist_second = (1 / second - e) ** 2
and then compare them:
if dist_first < dist_second:
print("First is closer.")
elif dist_second < dist_first:
print("Second is closer.")
else:
print("Draw.")

Related

Problems of defining a factorial function in python

I'm recently starting to learn coding in Python, this is the code that I tried to define a function that helps me to find the factorial of a number. Yet, this chunk of code always returns me the double of its factorial.
def factorial(x):
empty = None
try:
adj_x = int(x)
except:
print("Invalid Input")
if adj_x < 0:
print("Invalid Input")
elif adj_x == 0:
print(0)
else:
l_adj_x = adj_x - 1 # if input == 4, this is 3
r = range(1, l_adj_x) # 1, 2, 3
for k in r:
n = adj_x - k # 4-1 = 3, 4-2 = 2, 4-3 = 1
if empty is None:
empty = n
else:
empty = empty * n
n_adj_x = adj_x * empty * n
print(n_adj_x)
I realized that it is the problem of the n in this line:
n_adj_x = adj_x * empty * n
Based on my own understanding, the last n in the for-loop should be 1 (I took 4 as an example of my input and stated all the possible outcomes of the loop in the comments next to each line of code) , if so, why does it appear to be the double of the correct answer (when I include n in n_adj_x = adj_x * empty * n) since the n should equal to 1?
If what you are trying to get is the factorial here are some
examples:
Example 1
n = 10
factorial = 1
for i in range(1,n+1):
factorial *= i
print(factorial)
Example 2 <-- worst option
Slowest option and requires the most additional memory.
def fact(x):
if x <= 1:
return 1
return x * fact(x - 1)
print(fact(10))
Example 3 <-- Best option
import math
print(math.factorial(10))
This is the python libs built in function and probably performs better than my simple loop, however I have not tested it.

After inputting all the necessary values, python refuses to execute the while loop

I am writing a code for a class in which I have to create a code that approximates the root of a cubic function between an interval using bisection. I have written a code in which should preform that, however; after inputting values for the variables, it preforms the print command then breaks and stops just before the while command. The text cursor enters into a new line like I am supposed to input more info when it's supposed to be executing the while loop().
import sys
print('The function should be in the format: Ax^3 + Bx^2 + Cx + D. ')
A = float(input(' What is the value of A? '))
B = float(input(' What is the value of B? '))
C = float(input(' What is the value of C? '))
D = float(input(' What is the value of D? '))
a = float(input(' What is the value of the smallest x-value of your interval? '))
b = float(input(' What is the value of the largest x-value of your interval? '))
g = a > b
interval = (b - a) / 2
tolerance = 10 ** -6
print(interval)
if g:
print('b must be larger than a'), sys.exit()
while interval > tolerance:
iteration = 0
p = (a + b) / 2
f0p = A * (p ** 3) + B * (p ** 2) + C * p + D
if f0p == 0:
print('The root of the function is', p)
else:
if p < 0 and a > 0:
b = p
if p < 0 and b > 0:
a = p
if p > 0 and a < 0:
b = p
if p > 0 and b < 0:
a = p
iteration += 1
print('The root is x=', p, ',calculated in', iteration, 'iterations.')
I have tried changing indentation, and I've looked everywhere as to why the while loop would refuse to execute and the text cursor would drop down to a new line as if it wanted more input.
It isn't waiting for additional input. You never modify the interval value, so the while loop condition is always true, and the loop just continues.
Your while loop gets executed, it just never finishes

How to define a variable by an equation containing it? (Python)

I´m solving a problem in which i have to print all the fibonacci numbers such that:
a <= f <= b
And i would like to start them by the smallest fibonacci number that is greater than or equal to a, in order to make my program run faster. For that, i need to define a variable "n", such that the nth Fibonacci number satisfies the condition above (smallest one that is greater than or equal to a). To define such variable, i need to find the smallest "n" that satisfies the fibonacci(n) general term equation.
I tried to find it by making a for loop, but it just ends up being as slow as if i started to check from the first Fibonacci Number. Anyone has any ideas on how to define it efficiently?
P.S. Here is my attempted code:
from math import sqrt, log, ceil
def Fibo(n):
if n == 1: return 1
elif n == 2: return 2
return Fibo(n-1) + Fibo(n-2)
while True:
try:
a, b = [int(i) for i in input().split()]
cont = 0
phi = (sqrt(5) + 1) / 2
i = ceil(log(a * sqrt(5), phi))
if Fibo(i-1) >= a: i -= 1
elif Fibo(n) < a: i += 1
while True:
if a <= Fibo(i) <= b: cont += 1
elif Fibo(i) > b:
break
i -= 1
print(cont)
except input() == "0 0":
break
Probably the most useful formula for your purpose for F(n), the nth Fibonacci number, is
from math import sqrt
phi = (sqrt(5) + 1) / 2 # the golden ratio
F(n) = round(phi**n / sqrt(5))
Therefore, one formula to get the value of n for a given value of a is
from math import sqrt, log, ceil
phi = (sqrt(5) + 1) / 2 # the golden ratio
n = ceil(log(a * sqrt(5), phi))
Due to approximation and rounding issues, you should check the values of n-1, n, and n+1 to ensure you got exactly the desired value. If you do this often, you should pre-define variables holding the value of the golden ratio and of the square root of five. If your value of a is too large for the float type to store it accurately, you would need a more complicated routine to handle the larger number.

Logical thinking for a Calculation of Square root

I've been trying to decipher this problem for the last hour right now and having some trouble here. This is the problem
This method for calculating the square root of a number n starts by
making a (non zero) guess at the square root. It then uses the
original guess to calculate a new guess, according to the formula
newGuess = ((n / oldGuess) + oldGuess) / 2.0;
Have two variables oldGuess and newGuess. Initialize oldGuess to
n / 2.0 and calculate newGuess according to the above formula. Use
a while loop to iterate as long as the absolute value of the
difference between the oldGuess and newGuess is greater than
1.0E-06. Do not forget to reset the value of oldGuess to the
newGuess value in the while loop.
In your program you will prompt the user to enter a positive number.
If the number is negative, print an error message and ask the user to
try again. For a positive number, calculate the square root using the
above method. Find the difference between the square root you obtained
and the value obtained from using the exponentiation operator. Write
out the value the user entered, the square root you computed, and the
difference (your square root - n ** 0.5)
This is my program so far
def main():
n = eval(input("Enter a positive number: "))
while (n <= 0):
print ("Error please re-input")
n = eval(input("Enter a positive number: "))
oldGuess = n / 2.0
newGuess = ((n / oldGuess) + oldGuess) / 2.0;
difference = n - n ** 0.5
while (difference < 1 * 10 ** -6):
print ("Error")
difference = abs(n - n ** 0.5)
print ("Difference:", difference)
main()
So I don't really understand how we can tell the program to make a guess and then calculate the square root of variable n. I don't even think my while statements are right in this context. I don't use the already embedded function the squareroot built into python so it has to be done manually I believe still lost on what it means by the guess function.
while True:
n = float(input("Enter a positive number: "))
if n > 0:
break
print ("Error please re-input")
oldGuess = n / 2.0
while True:
newGuess = ((n / oldGuess) + oldGuess) / 2.0;
oldGuess = newGuess
if -1e-6 < n - newGuess * newGuess < 1e-6:
break
print ("Difference:", abs(n ** .5 - newGuess))
Change those eval()s to float()s. eval() executes any code it's handed, so that means your user could type something malicious there.
Now, use this for the second part:
oldGuess = n / 2.0
newGuess = ((n / oldGuess) + oldGuess) / 2.0
while (abs(oldGuess - newGuess) > 1e-06):
oldGuess, newGuess = newGuess, ((n / oldGuess) + oldGuess) / 2.0
print("Guess: " + str(n))
print("My root: " + str(newGuess))
print("Accuracy: " + str(newGuess - (n**0.5)))
That comma syntax is a Python idiom useful for swapping values without having to do:
temp = new
new = old * something
old = temp
Your condition for the while loop is looking to end looping when your difference is less than that (very small) value. So you will loop so long as it is greater than that.
Note: you can also use math.sqrt(n) instead of n ** 0.5. You'll have to import math.
If you want to see what your program is doing, try printing the values of oldGuess and newGuess within the while loop. You'll see it's changing them until you've arrived at your answer.
Edit:
I notice that you seem to be tripped up on why you have to do oldGuess = newGuess. Let me explain: the = operator is not the same as the equals sign in mathematics. The equals sign says that the thing on the left is the same thing as the thing on the right; i.e. they are equivalent. In Python, the = operator says "give the thing on the left the same value as the thing on the right." It is called the assignment operator. You are thinking of the == operator, which tests for equivalency (basically).
>>> a = 10
>>> b = 4
>>> b = a
>>> b
10
>>> a == b
True
>>> c = 6
>>> b = c
>>> b
6
>>> a == b
False
>>> b == c
True
>>> a == c
False
>>> a,b,c
(10, 6, 6)
As you can see, when you use the = operator, you don't "link" the variables together, saying that they are now the same thing. If you set b = a and then set b = c, b == a becomes false because b does not have the same value as a anymore. a does not change either, because b was assigned its value, not the other way around. Think of the = operator looking like <- instead (I think some languages actually use this as the assignment operator).
Why does this matter? Well, you do assign something new to a variable, you forget the old value. Unless you have another variable storing the same value, it's lost forever. Your assignment says to update the oldGuess to the previous newGuess. In other words, if your guesses were "a", "b", "c", "d", then you'd start with oldGuess as "a" and from there compute newGuess as "b". Since this would obviously not be the correct guess, you say the oldGuess is now what the newGuess just was - "b", and you compute the next newGuess, which is "c".
You need the value of oldGuess to compute the value of newGuess. But, you need the value of newGuess (before you changed it) to update the value of oldGuess. It's a catch-22, unless you store the previous value of newGuess as I showed above (as the swapping example). That is why you need this.
So I figured it out thanks guys for help. I didn't know we can't post homework questions on here but I am trying to definitely learn how to code so I can get better at it. Here was my final solution.
def main():
n = float(input("Enter a positive number: "))
while (n <= 0):
print ("Error please re-input")
n = eval(input("Enter a positive number: "))
oldGuess = n / 2.0
newGuess = 0
difference = 10
while (difference >= 1 * 10 ** -6):
newGuess = ((n / oldGuess) + oldGuess) / 2.0
difference = abs(newGuess - oldGuess)
oldGuess = newGuess
print ("Square Root is: ", newGuess)
differenceSqrt = newGuess - n ** 0.5
print ("Difference is: ", differenceSqrt)
main()
I still don't know how to use breaks effectively so thanks gnibbler but couldn't really follow your code too well. (New to this, sorry)

python lists append

I was about to code a program which evaluates a polynomial. But the code below is just a try-out for that. The code below gives an output that stops when "counter = t"... I want it to give an output up to when counter=0. How can that be? I wanted to treat every number(input) as a coefficient of the polynomial. If I was successful doing this, I'm planning to make a list then for every, say, element in the list, I will then multiply it to a certain number raised to its index then add them up so that I've evaluated a polynomial.. Am I clear? And will my plan work out?? Thank you so much.. Please help..
t = input("Enter degree of Polynomial: ")
while t < 0:
print ("Not possible! ")
t = input("Enter degree of Polynomial: ")
counter = 0
while counter < t:
x = input("n: ")
if x <= 0:
print "Not possible!"
else:
print x**t
t-=1
counter += 1
THe ouput goes like this:
Enter degree of polynomial: 5
n: 5
3125
n:4
256
n:3
27
then it ends.. it should continue asking for an input n up to five times..
Try to use raw_input() and keep in mind that raw_input() returns always a string. So you have to convert the returned string to an integer like:
>>> x = int(raw_input("foo: "))
Then it is possible to test something like x > 2 etc. Without casting to integers the following would happen:
>>> "2" > 1
True
>>> "2" > 3
True
First of all: Well done - it's only a little mistake: Remove the "syntactic whitespace" in your last line, or remove it completly
Secondly: Don't forget to add the values ;-) - and with regards to your headline, this is best done with a python list.
The problem seems (to me) that you are having the loop depend on 2 variables, where you perhaps expected it to be only dependent on 1.
Perhaps this works a little better:
while t > 0:
x = input("n: ")
if x <= 0:
print "Not possible!"
else:
print x**t
t-=1
Something like this?
while True:
degree = int(raw_input("Enter degree of Polynomial: "))
if degree >= 0:
break
print ("Not possible!")
x = float(raw_input("x = "))
y = 0.0
for exponent in reversed(range(degree)):
k = float(raw_input("k[{0}] = ".format(exponent)))
y += k * (x ** exponent)
print("y = ", y)
This solves a polynomial of the form:
y = (k[N-1] * (x ^ N-1) + (k[N-2] * (x ^ N-2) + ... + k[0]

Categories

Resources