This is taken from a question paper for Python programming. I have the following code:
import numpy as np
from math import sin, pi
#Part a:
def f(x):
return 2*x - x**2
def g(p,x):
return p*sin(pi*x/2)
def hsum(p):
s = 0
for i,j in zip(np.arange(0,3,2E-4),np.arange(2E-4,3,2E-4)):
delx = j - i
ab = abs(f(i)-g(p,i))
s += ab*delx
return s
#print hsum(1)
#print hsum(0)
#Part b:
h = hsum(0)
P = []
Q = []
for p in np.arange(0,1.1,1E-3):
k = hsum(p)
if k<h:
h = k
P.append(hsum(p))
Q.append(p)
print h
print min(P)
g = min(P)
t = P.index(g)
#print t
#print Q
print Q[t]
However, upon running it, the program returns a value of 0.001 for the so-called optimal P. This value should be close to 1 and before 1.1, according to the problem statement.
I thought that there may be a problem with floating points, but any combination I try gives me the same answer. Any suggestions?
EDIT: Using all the suggestions provided, I edited the original code and this one, although rather slow (runtime of 9:58!!), provides the correct answer of 1.071 Thanks for all the help. :D
In hsum
, you reset s
to 0
in every loop iteration. You should probably move that up, outside the loop.
In your code to find the best fit, you're appending the p values to P, but you don't keep any information about the quality of the fit. min(P)
finds the lowest p, not the one that fits best. Store (p, hsum(p))
tuples and find the minimum by the H(p) values. The min function takes a key
argument that can help you with that. (With a bit of simplification, you wouldn't even need to make the tuples.)