newtons method defined function while loop no output - python

I'm very new to coding and am working on a project where I write a code to perform newtons method for lots of different functions. The code I wrote to do newtons method is as follows:
def fnewton(function, dx, x):
#defined the functions that need to be evaluated so that this code can be applied to any function I call
def f(x):
f=eval(function)
return f
#eval is used to evaluate whatever I put in the function place when I recall fnewton
#this won't work without eval to run the functions
def df(x):
df=eval(dx)
return df
n=0
min=.000001
guess=2
xi_1=guess
#defining these variables before Fnewton so I can use them in print
while np.absolute((xi_1))>min:
#basically this means that you continue the process until funct/der is greater than the tolerance
n=n+1 #helps keep track over how many times I iterated
x=xi_1-f(xi_1)/df(xi_1) #this is the newton eqn
xi_1=x
print('the root is at:')
print(x)
print('after this many iterations:')
print(n)
I am trying to call on this function to operate on functions I defined before it by using the command:
fnewton("a(x)", "dadx(x)",2)
Once I added the two it would run(and tell me variables weren't defined) but now it just runs forever and never computes anything. please help, did I code wrong?
ps. a(x) and dadx(x) are:
def a(x):
f=np.exp(np.exp(-x))-x**2+x
return(f)
def dadx(x):
f=(a(x+.01)-a(x))/.01
return(f)

I executed the code you loop stuck at value 1.7039784148789716, your logic which says while np.absolute(xi_1)>min1: seems not working
try printing values inside the loop as below
while np.absolute(xi_1)>min1:
#basically this means that you continue the process until funct/der is greater than the tolerance
n=n+1 #helps keep track over how many times I iterated
x=xi_1-f(xi_1)/df(xi_1) #this is the newton eqn
xi_1=x
print(np.absolute(xi_1))
and find the proper while expression to suite your result

I think you meant while np.absolute(f(xi_1))>min:
PS: just refrain yourself from using functions like eval() in python, it makes your code a lot harder to debug

Best to write your f and df as discrete functions then pass references to them to fnewton(). In this way the implementation of fnewton() remains constant and you just have to pass your estimate and f and df references. You can reasonably hard-code Euler's Number for this trivial case which avoids the need to import numpy
e = 2.718281828459045
def f(x):
return e**(e**(-x))-x**2+x
def df(x):
return (f(x+.01)-f(x))/.01
def fnewton(x0, f, df, tolerance=0.0001):
if abs(fx0 := f(x0)) < tolerance:
return x0
return newton(x0 - fx0/df(x0), f, df, tolerance)
print(fnewton(1.5, f, df))
Output:
1.7039788103083038

Related

Wrapper Function in Python

#***This code uses wrapper function to print the phone number in a
standard format with country code (if not supplied in the input)***
def ori_func(a):
mm=[]
def wraap(*args):
for k in args:
for i in k:
#print(i)
if len(str(i))==10:
mm.append("+91"+str(i))
elif str(i)[0]=="0" and len(str(i))==11:
mm.append("+91"+str(i)[1:])
#elif len(str(i))==12 and i[0]=="+":
# mm.append(i)
elif len(str(i)) == 12:
mm.append("+"+str(i))
#print (mm)
return a(mm)
return wraap
#ori_func
def srt_phone(mm):
#sorted(int(mm))
for j in sorted(mm):
cc=str(j)[:3]
mmn1=str(j)[3:8]
mmn2=str(j)[8:]
print (cc+" "+mmn1+" "+mmn2)
m=[1234567891, 912345678923, +919876543219,"07418529637"]
srt_phone(m)
This code works fine as per my knowledge. However I need you to look-through my code and let me know my level of Wrapper function knowledge is correct
When I pass a list to wrapper function, do I need to really use 2 "For" loops in wrapper function like I did? Is there any other way?
When we asked to get the phone number as input in INT format,how to handle with the input that starts with 0?
Thanks
Yes. There are other ways but that way is pretty clean.
You can't, and I suggest not treating phone numbers as numbers because they aren't real numbers. Real numbers can't start with a + or a 0.
Your code looks fine to me; I'd have done a few things differently but that's just personal preference. I do recommend that you look into using #functools.wraps(a) on your inner function.

Python Recursion Issue; I Can’t Change My Hard Code Into a Recursive Function

beside(picture,picture) #beside takes two pictures as arguments and prints them side by side in a 1:1 ratio.
stackn(n,picture) #stackn takes a number and a picture as arguments and prints n number of shapes in a vertical row.
show(picture) #show takes a picture as an argument and shows it on the canvas
In this case picture is the parameter heart_bb:
(n=2)# show(beside((stackn(1,heart_bb)),(stackn(2,heart_bb))))
(n=3)# show(beside((stackn(1,heart_bb)),(beside((stackn(2,heart_bb)),(stackn(4,heart_bb))))))
(n=4)# show(beside((stackn(1,heart_bb)),(beside((stackn(2,heart_bb)),(beside((stackn(4,heart_bb)),(stackn(8,heart_bb))))))))
My task is to come up with a recursive function(I’m going to call it test):
def test(n, picture):
I need this function to return the corresponding line of code shown above. For example, test(3,heart_bb) should return the line of code for n=3. Likewise, test(4,heart_bb) will return the line of code for n=4.
It has to work for any n>1, but after n=5 coding it gets really tedious.
def fractal(picture,n):
if n==1:
return(picture)
else:
return(beside((fractal(picture,(n-1))),(stackn((2**(n-1)), (picture)))))
I suppose you mainly need an idea of how you can do it and not a way to find someone that writes the code for you.
I would suggest to use a n-ary beside operation in place of your one, in such a way to simplify the code for n=2,3,4,... Since I cannot modify it I will define a new one in terms of your binary operation in this way:
def beside_pictures(pictures):
assert len(pictures) > 0
result = pictures[-1]
for tmp in pictures[:-1:-1]: # reverse order, starting from -1
result = beside(tmp, result)
return result
Now we are ready to transform your test function in a one line function:
def test(n, picture):
assert n > 0
show(beside_pictures([stackn(2**i,picture) for i in range(n)]))
UPDATE: If the requirement to have a recursive function is strict, one possible solution is the following one:
def test(n, picture):
if n == 1:
return stackn(1,picture)
return beside(test(n-1, picture), stackn(2**(n-1),picture))

Saving output of a function as a variable and using it in another function

I'm new to programming, so this question might be dumb.
I need to introduce the value of Tr1 into the Bzero1 function. When I run the module I get the result below:
.
The program is not running the Bzero1 function and I'm not sure why. Is it because I am not introducing the Tr1 value correctly or something else? I want Bzero1 to perform the operation 0.083-(0.422/Tr1**1.6), with Tr1 obtained from the result of T/Tc1.
I would appreciate your help a lot.
T = float(input("Introduce system temperature in Kelvin: "))
print("System temperature is: ", T)
Tc1 = float(input("Introduce critical temperature of component 1: "))
print("Critical temperature of component 1 is: ", Tc1)
def Tr1(T, Tc1):
print("Relative temperature 1: ", T/Tc1)
Tr1 = Tr1(T, Tc1)
def Bzero1(Tr1):
print("Bzero 1: ", 0.083-(0.422/Tr1**1.6))
Do not replace Tr1 function value, to avoid such replacement change:
Tr1_value = Tr1(T, Tc1)
Call Bzero1 function with code:
Bzero1(Tr1_value)
Modify Tr1 to return value:
def Tr1(T, Tc1):
result = T/Tc1
print("Relative temperature 1: ", result)
return result
Also, let me suggest you to take a look on python official tutorial - there you can learn a lot about python ...
Good Luck !
def is only defining a function, not calling it. E.g.
def foo(a):
print a * 2
means there is now a function foo that takes argument a. The a in foo(a) is the name of the variable inside the function.
So in your case
def Bzero1(Tr1):
print("Bzero 1: ", 0.083-(0.422/Tr1**1.6))
defines the function Bzero1 as taking argument Tr1, but doesn't call it. You need to call the function, just like you called Tr1:
Bzero1(Tr1)
You can see that this way it becomes confusing quite quickly on which is a variable outside of your function, and which are variables inside functions. Therefore it is better to use different names for variables in your outer program v.s. those inside functions.
Here are a few more best practices that you might find useful:
It is generally better to first define all functions and then execute the program's main code, as opposed to intermixing function definitions and the main program.
Another best practice is to make functions only calculate output from inputs, and handle output somewhere else. This way you get to reuse your functions in other parts of your program while always keeping control of when and what to output to the user.
Finally, you shouldn't generally reassign names, e.g. Tr1 = Tr1(...) means that Tr1 is now no longer the name of the function but the name of the result returned by Tr1. In short, use different names for different things.
Applying these tips, your code might look as follows:
# function definitions first
def Tr1(vt, vtc1):
return vt/vtc1
def Bzero1(vtr1):
return 0.083-(0.422 / vtr1 ** 1.6)
# get user input
T = float(input("Introduce system temperature in Kelvin: "))
print("System temperature is: ", T)
vTc1 = float(input("Introduce critical temperature of component 1: "))
print("Critical temperature of component 1 is: ", vTc1)
# run calculations
vTr1 = Tr1(T, vTc1)
vBz1 = Bzero1(vTr1)
# print output
print("Relative temperature 1: ", vTr1)
print("Bzero 1: ", vBz1)
Note
Since I don't know the semantic meaning of your variables I have just used small letter v as a prefix - in general it is better to use meaningful names like temperature or temp1 and temp2 etc. Programs are not math papers.

Python. Project Euler Q35. Got a solution but I don't understand why other method doesn't work.

def rot_dig(x):
y=''
output=[x]
listing=list(x)
for i in range(1,len(x)):
listing.append(listing[0])
del(listing[0])
for i in listing:
y=y+i
output.append(y)
y=''
return output
import math
def prime_is(x,prime):
for m in prime:
if m&lt=math.sqrt(x):
if x%m==0:
return False
else:
return True
prime=[2]
for x in range(3,1000000):
if prime_is(x,prime):
prime.append(x)
primestr=[]
for x in prime:
primestr.append(str(x))
sums=0
for x in primestr:
count=0
for y in rot_dig(x):
if y in primestr:
count+=1
if count==len(x):
sums+=1
else:
for y in rot_dig(x):
if y in primestr:
primestr.remove(y)
print sums
When run with the bold code the solutions miss the final rotation. So if it looks at say 1193, it includes 1193, 3119, 9311 but not 1931. I have spent a while trying to work out why but I don't get it.
I have since edited the code to make it much quicker and solved the problem I had by simply removing the block of code, but I can't understand why it happens since surely that block of code will only be executed on non circular primes.
It's probably because your outer loop is for x in primestr: and the marked code removes items from primestr. You don't want to change primestr while looping over it that way. You could use a loop like while i < len(primestr) instead.
Some other improvements would be to compute sqrt outside the loop; to use a list comprehension instead of a loop to create primestr; and especially to use string slicing in rot_dig, it's way more complicated than it needs to be.

python, how to write an iterative function

I am quering a database for some paramaters which depend on a attribute called count! count can be incremented incase the 1st query does not return anything. Here is a sample code
sls = {(213.243, 55.556): {}, (217.193, 55.793): {}, (213.403, 55.369): {}}
for key in sls.keys:
if not sls[key]:
ra, dec = key[0], key[1]
search_from_sourcelist(sl, ra,dec)
count = 1
def search_from_sourcelist(sl, ra,dec):
dist = count/3600.0
sls[(ra,dec)] = sl.sources.area_search(Area=(ra,dec,dist))
return
Incase i run the method search_from_sourcelist, and it doesnt return anything, i would like to increment count, and do the query again. This is to be done for all keys in sls dictionary, untill all the keys have a value!!
Here is the most fundamental recursive function
def countdown(n):
if n == 0:
return "Blastoff"
else:
print "T minus %s" % n
return countdown(n-1)
You will notice that countdown returns itself with a modified argument, in this case n but -1, so if you actually followed this all the way through you would get
(-> indicates a call)
countdown(5) -> countdown(4) -> countdown(3) -> countdown(2) -> countdown(1) -> countdown(0) #stop
So now you understand what a recursive function looks like you realize you never actually return a call of your own function, thus your code is not recursive
We use recursion because we want to boil a task down to its simplest form then work from there, so a good example of this would be the mcnuggets problem. So you need to tell us what you are trying to achieve and how it can be made a smaller problem (or more importantly why.) Are you sure you cannot do this iteratively? remember you don't want to blow your stack depth because python is NOT tail recursive by standard
Recursion is useful when you find a way to reduce the initial problem to a "smaller version of itself".
The standard example is the factorial function
def fac(n):
return n * fac(n-1) if n > 1 else 1
Here you reduce the problem of calculating the factorial of n to calculating the factorial of n-1.
In your code there is no such "reduction". You just increment a value and start the same problem over again. Thus, I recommend you solve it iteratively.
I'm not sure that you need a recursive algorithm for this.
Incase i run the method search_from_sourcelist, and it doesnt return anything, i would like to increment count, and do the query again. This can be done with a while loop as follows:
for key, value in sls.iteritems():
if not value:
ra, dec = key[0], key[1]
count = 1
while not search_from_sourcelist(sls, ra, dec):
count += 1
But if you really do want to do this recursively, you can do it as follows, leave a comment and I'll write it up.
Further, you should look into your search_from_sourcelist function, as it always returns None

Categories