Also, calculate (p0 * math.e) once before the for() instead of every pass calculating it again. You should be using one for() loop, since they all do the same thing.
numeratorPos1 = 0
numeratorPos2 = 0
denominatorPos = 0
p0_math_e = p0 * math.e
for x in range(0, n):
y = p0_math_e**(-(decay * x))
numeratorPos += ((x**2)*y)
numeratorPos += (y*(math.log(y)))
denominatorPos += y
#
# etc.
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
It is considered bad, because this time for example you had same bug repeated 14 times in your code, for example. Instead insert print functions and any input statement for pause or use debugger break points and watches.
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
Here is another way to code this
import math
def fsum(f, g, pairs):
return sum(f(x)*g(y) for (x,y) in pairs)
def one(x):
return 1.0
def ident(x):
return x
def square(x):
return x*x
def plog(x):
return x * math.log(x)
def fit(pairs):
pairs = list(pairs)
si, op, ii, ip, oi = [ fsum(f, g, pairs) for (f, g) in (
(square, ident),
(one, plog),
(ident, ident),
(ident, plog),
(one, ident),
)]
den = float(oi * si - ii ** 2)
a = (si * op - ii * ip)/den
b = (oi * ip - ii * op)/den
return a, b
def gen_pairs():
n = 800
p0 = (5*(10**6))
decay = (1.16*(10**-3))
print("expected b: %.16f" % (-decay * math.log(p0*math.e)))
for i in range(n):
y = (p0 * math.e)**(-(decay * i))
yield (i, y)
def main():
a, b = fit(gen_pairs())
print(a)
print(b)
if __name__ == "__main__":
main()
"""
my output -->
expected b: -0.0190529402256621
-2.40854223893e-16 # expected a is 0.0
-0.0190529402257
"""
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691