Related
from pylab import *
no_steps = 10000
number = random()
position = zeros(no_steps)
position[0] = 0
time = zeros(no_steps)
time[0] = 0
for i in range(1, no_steps):
time[i] = time[i-1] + 1
if number >= 0.5:
position[i] = position[i-1] + 1
number = random()
else:
position[i] = position[i-1] - 1
number = random()
plot(time, position)
number2 = random()
position2 = zeros(no_steps)
position2[0] = 0
time2 = zeros(no_steps)
time2[0] = 0
for t2 in range(1, no_steps):
time2[t2] = time[t2-1] + 1
if number2 >= 0.5:
position2[t2] = position2[t2-1] + 1
number2 = random()
else:
position2[t2] = position[t2-1] - 1
number2 = random()
plot(time2,position2)
This is supposed to generate random walks by generating a random number each time and checking the conditions. Therefore I assumed that if it works for one walk I can just add more of the same and put them all on the same graph at the end. However, apparently that's not how this works and the graphs that do end up being plotted are extremely similar with the difference in the positions being one of -2 for some reason. The code if I run the blocks separately from their own program will generate two completely different walks, it's just when I put them together that it stops working as intended. What exactly am I missing?
You've accidentally reused variables from the first plot:
for t2 in range(1, no_steps):
time2[t2] = time[t2-1] + 1
^^^^^ ^^^^
if number2 >= 0.5:
position2[t2] = position2[t2-1] + 1
number2 = random()
else:
position2[t2] = position[t2-1] - 1
^^^^^^^^^ ^^^^^^^^
number2 = random()
plot(time2,position2)
I would generate the random walk with a function so you don't have to worry about renaming variables like this:
import numpy
from pylab import *
no_steps = 10000
def random_walk(no_steps):
# 2 * [0, 1] - 1 -> [0, 2] - 1 -> [-1, 1]
directions = 2 * numpy.random.randint(0, 2, size=(1, no_steps)) - 1
positions = numpy.cumsum(directions)
positions -= positions[0] # To make it start from zero
return positions
time1 = numpy.arange(0, no_steps)
plot(time1, random_walk(no_steps))
savefig('1.png')
clf()
time2 = numpy.arange(0, no_steps)
plot(time2, random_walk(no_steps))
savefig('2.png')
I'm running a population model, and the wrong numbers always come out because I'm setting the variables to new values, but then when I want to use the old variables, the loop automatically updates itself and uses the new ones.
juvenile_population = 10
adult_population = 10
senile_population = 1
juvenile_survival = 1
adult_survival = 1
senile_survival = 0
birth_rate = 2
generations = 5
counter = 0
while counter < generations:
juvenile_population = adult_population * birth_rate
adult_population = juvenile_population * juvenile_survival
senile_population = (adult_population * adult_survival) (senile_population * senile_survival)
total_population = juvenile_population + adult_population + senile_population
print("Juvenile: ",juvenile_population)
print("Adult: ",adult_population)
print("Senile: ",senile_population)
print("Total: ",total_population)
counter += 1
A friend said to set new named variables, but then after one loop, won't you get the same problem again? I want the variables to update, but only after they've been printed, if that makes sense.
Any suggestions?
You are overwriting the existing values with new values. With Python you can merge all four lines into one like this:
juvenile_population, adult_population, senile_population, total_population = adult_population * birth_rate, juvenile_population * juvenile_survival, (adult_population * adult_survival) (senile_population * senile_survival), juvenile_population + adult_population + senile_population
This will assign all the values at once, without overwriting them first.
Per #Selcuk, you could use variable unpacking directly, but even with nicer formatting it looks unwieldly:
juvenile_population, adult_population, senile_population, total_population = (adult_population * birth_rate,
juvenile_population * juvenile_survival,
(adult_population * adult_survival) (senile_population * senile_survival),
juvenile_population + adult_population + senile_population)
My suggestion would be to either write a helper function, and keep "like" values in a dictionary like so:
populations = {'juvenile': 10,
'adult': 10,
'senile': 1
}
survivals = {'juvenile': 1,
'adult': 1,
'senile': 0}
birth_rate = 2
generations = 5
def update_population(pops):
juvie = pops['adult'] * birth_rate
adults = pops['juvenile'] * survivals['juvenile']
seniles = pops['adult'] * survivals['adult'] + (pops['senile'] * survivals['senile'])
return {k:v for k,v in zip(['juvenile','adult','senile'],[juvie,adults,seniles])}
counter = 0
while counter < generations:
populations = update_population(populations.copy())
total_population = sum(populations.values())
print("Juvenile: ",populations['juvenile'])
print("Adult: ",populations['adult'])
print("Senile: ",populations['senile'])
print("Total: ",total_population)
counter += 1
I am trying to make a function which can print a polynomial of order n of x,y
i.e. poly(x,y,1) will output c[0] + c[1]*x + c[2]*y
i.e. poly(x,y,2) will output c[0] + c[1]*x + c[2]*y + c[3]*x**2 + c[4]*y**2 + c[5]*x*y
Could you give me some ideas? Maybe itertools?
You could try to start from something like
def poly(x,y,n):
counter = 0
for nc in range(n+1):
for i in range(nc+1):
print "c[", counter, "]",
print " * ", x, "**", i,
print " * ", y, "**", nc-i,
print " + ",
counter += 1
For example
poly("x", "y", 2)
will produce
c[ 0 ] * x ** 0 * y ** 0 + c[ 1 ] * x ** 0 * y ** 1 + c[ 2 ] * x ** 1 * y ** 0 + c[ 3 ] * x ** 0 * y ** 2 + c[ 4 ] * x ** 1 * y ** 1 + c[ 5 ] * x ** 2 * y ** 0 +
Build in ifs, if you want to suppress undesired output.
Since you wanted a functional solution with itertools, here's a one-liner:
import itertools as itt
from collections import Counter
n = 3
xy = ("x", "y") # list of variables may be extended indefinitely
poly = '+'.join(itt.starmap(lambda u, t: u+"*"+t if t else u, zip(map(lambda v: "C["+str(v)+"]", itt.count()),map(lambda z: "*".join(z), map(lambda x: tuple(map(lambda y: "**".join(map(str, filter(lambda w: w!=1, y))), x)), map(dict.items, (map(Counter, itt.chain.from_iterable(itt.combinations_with_replacement(xy, i) for i in range(n+1))))))))))
That would give you
C[0]+C[1]*x+C[2]*y+C[3]*x**2+C[4]*y*x+C[5]*y**2+C[6]*x**3+C[7]*y*x**2+C[8]*y**2*x+C[9]*y**3
Note, the order of coefficients is slightly different. This will work not only for any n, but also for any number of variables (x, y, z, etc...)
Just for laughs
Slightly more generalized:
from itertools import product
def make_clause(c, vars, pows):
c = ['c[{}]'.format(c)]
vp = (['', '{}', '({}**{})'][min(p,2)].format(v,p) for v,p in zip(vars,pows))
return '*'.join(c + [s for s in vp if s])
def poly(vars, max_power):
res = (make_clause(c, vars, pows) for c,pows in enumerate(product(*(range(max_power+1) for v in vars))))
return ' + '.join(res)
then poly(['x', 'y'], 2) returns
"c[0] + c[1]*y + c[2]*(y**2) + c[3]*x + c[4]*x*y + c[5]*x*(y**2) + c[6]*(x**2) + c[7]*(x**2)*y + c[8]*(x**2)*(y**2)"
(Python) Given two numbers A and B. I need to find all nested "groups" of numbers:
range(2169800, 2171194)
leading numbers: 21698XX, 21699XX, 2170XX, 21710XX, 217110X, 217111X,
217112X, 217113X, 217114X, 217115X, 217116X, 217117X, 217118X, 2171190X,
2171191X, 2171192X, 2171193X, 2171194X
or like this:
range(1000, 1452)
leading numbers: 10XX, 11XX, 12XX, 13XX, 140X, 141X, 142X, 143X,
144X, 1450, 1451, 1452
Harder than it first looked - pretty sure this is solid and will handle most boundary conditions. :) (There are few!!)
def leading(a, b):
# generate digit pairs a=123, b=456 -> [(1, 4), (2, 5), (3, 6)]
zip_digits = zip(str(a), str(b))
zip_digits = map(lambda (x,y):(int(x), int(y)), zip_digits)
# this ignores problems where the last matching digits are 0 and 9
# leading (12000, 12999) is same as leading(12, 12)
while(zip_digits[-1] == (0,9)):
zip_digits.pop()
# start recursion
return compute_leading(zip_digits)
def compute_leading(zip_digits):
if(len(zip_digits) == 1): # 1 digit case is simple!! :)
(a,b) = zip_digits.pop()
return range(a, b+1)
#now we partition the problem
# given leading(123,456) we decompose this into 3 problems
# lows -> leading(123,129)
# middle -> leading(130,449) which we can recurse to leading(13,44)
# highs -> leading(450,456)
last_digits = zip_digits.pop()
low_prefix = reduce(lambda x, y : 10 * x + y, [tup[0] for tup in zip_digits]) * 10 # base for lows e.g. 120
high_prefix = reduce(lambda x, y : 10 * x + y, [tup[1] for tup in zip_digits]) * 10 # base for highs e.g. 450
lows = range(low_prefix + last_digits[0], low_prefix + 10)
highs = range(high_prefix + 0, high_prefix + last_digits[1] + 1)
#check for boundary cases where lows or highs have all ten digits
(a,b) = zip_digits.pop() # pop last digits of middle so they can be adjusted
if len(lows) == 10:
lows = []
else:
a = a + 1
if len(highs) == 10:
highs = []
else:
b = b - 1
zip_digits.append((a,b)) # push back last digits of middle after adjustments
return lows + compute_leading(zip_digits) + highs # and recurse - woohoo!!
print leading(199,411)
print leading(2169800, 2171194)
print leading(1000, 1452)
def foo(start, end):
index = 0
is_lower = False
while index < len(start):
if is_lower and start[index] == '0':
break
if not is_lower and start[index] < end[index]:
first_lower = index
is_lower = True
index += 1
return index-1, first_lower
start = '2169800'
end = '2171194'
result = []
while int(start) < int(end):
index, first_lower = foo(start, end)
range_end = index > first_lower and 10 or int(end[first_lower])
for x in range(int(start[index]), range_end):
result.append(start[:index] + str(x) + 'X'*(len(start)-index-1))
if range_end == 10:
start = str(int(start[:index])+1)+'0'+start[index+1:]
else:
start = start[:index] + str(range_end) + start[index+1:]
result.append(end)
print "Leading numbers:"
print result
I test the examples you've given, it is right. Hope this will help you
This should give you a good starting point :
def leading(start, end):
leading = []
hundreds = start // 100
while (end - hundreds * 100) > 100:
i = hundreds * 100
leading.append(range(i,i+100))
hundreds += 1
c = hundreds * 100
tens = 1
while (end - c - tens * 10) > 10:
i = c + tens * 10
leading.append(range(i, i + 10))
tens += 1
c += tens * 10
ones = 1
while (end - c - ones) > 0:
i = c + ones
leading.append(i)
ones += 1
leading.append(end)
return leading
Ok, the whole could be one loop-level deeper. But I thought it might be clearer this way. Hope, this helps you...
Update :
Now I see what you want. Furthermore, maria's code doesn't seem to be working for me. (Sorry...)
So please consider the following code :
def leading(start, end):
depth = 2
while 10 ** depth > end : depth -=1
leading = []
const = 0
coeff = start // 10 ** depth
while depth >= 0:
while (end - const - coeff * 10 ** depth) >= 10 ** depth:
leading.append(str(const / 10 ** depth + coeff) + "X" * depth)
coeff += 1
const += coeff * 10 ** depth
coeff = 0
depth -= 1
leading.append(end)
return leading
print leading(199,411)
print leading(2169800, 2171194)
print leading(1000, 1453)
print leading(1,12)
Now, let me try to explain the approach here.
The algorithm will try to find "end" starting from value "start" and check whether "end" is in the next 10^2 (which is 100 in this case). If it fails, it will make a leap of 10^2 until it succeeds. When it succeeds it will go one depth level lower. That is, it will make leaps one order of magnitude smaller. And loop that way until the depth is equal to zero (= leaps of 10^0 = 1). The algorithm stops when it reaches the "end" value.
You may also notice that I have the implemented the wrapping loop I mentioned so it is now possible to define the starting depth (or leap size) in a variable.
The first while loop makes sure the first leap does not overshoot the "end" value.
If you have any questions, just feel free to ask.
I have been thinking about this issue and I can't figure it out. Perhaps you can assist me. The problem is my code isn't working to output 1000 digits of pi in the Python coding language.
Here's my code:
def make_pi():
q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
while True:
if 4 * q + r - t < m * t:
yield m
q, r, t, k, m, x = (10*q, 10*(r-m*t), t, k, (10*(3*q+r))//t - 10*m, x)
else:
q, r, t, k, m, x = (q*k, (2*q+r)*x, t*x, k+1, (q*(7*k+2)+r*x)//(t*x), x+2)
digits = make_pi()
pi_list = []
my_array = []
for i in range(1000):
my_array.append(str("hello, I'm an element in an array \n" ))
big_string = "".join(my_array)
print "here is a big string:\n %s" % big_string
I know this code can be fixed to work, but I'm not sure what to fix... The print statement saying here is a big string and the my_array.append(str("hello, im an element in an array \n)) is just a filler for now. I know how all the code is used to work, but like I said before, I can't get it to shoot out that code.
If you don't want to implement your own algorithm, you can use mpmath.
try:
# import version included with old SymPy
from sympy.mpmath import mp
except ImportError:
# import newer version
from mpmath import mp
mp.dps = 1000 # set number of digits
print(mp.pi) # print pi to a thousand places
Reference
Update: Code supports older and newer installations of SymPy (see comment).*
Run this
def make_pi():
q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
for j in range(1000):
if 4 * q + r - t < m * t:
yield m
q, r, t, k, m, x = 10*q, 10*(r-m*t), t, k, (10*(3*q+r))//t - 10*m, x
else:
q, r, t, k, m, x = q*k, (2*q+r)*x, t*x, k+1, (q*(7*k+2)+r*x)//(t*x), x+2
my_array = []
for i in make_pi():
my_array.append(str(i))
my_array = my_array[:1] + ['.'] + my_array[1:]
big_string = "".join(my_array)
print "here is a big string:\n %s" % big_string
And read about yield operator from here:
What does the "yield" keyword do?
Here is the answer:
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337
The accepted answer is incorrect, as noted in comments.
The OP's code appears to be based on an implementation of Spigot's algorithm copied from here.
To fix the code per the OP's question (although I renamed the variables and functions to match what they were in the original source), one solution might be:
#!/usr/bin/env python
DIGITS = 1000
def pi_digits(x):
"""Generate x digits of Pi."""
q,r,t,k,n,l = 1,0,1,1,3,3
while x >= 0:
if 4*q+r-t < x*t:
yield n
x -= 1
q,r,t,k,n,l = 10*q, 10*(r-n*t), t, k, (10*(3*q + r))/t-10*n, l
else:
q,r,t,k,n,l = q*k, (2*q+r)*l, t*l, k+1, (q*(7*k+2)+r*l)/(t*l), l+2
digits = [str(n) for n in list(pi_digits(DIGITS))]
print("%s.%s\n" % (digits.pop(0), "".join(digits)))
Also, here is a much faster* implementation, also apparently based on Spigot's algorithm:
#!/usr/bin/env python
DIGITS = 1000
def pi_digits(x):
"""Generate x digits of Pi."""
k,a,b,a1,b1 = 2,4,1,12,4
while x > 0:
p,q,k = k * k, 2 * k + 1, k + 1
a,b,a1,b1 = a1, b1, p*a + q*a1, p*b + q*b1
d,d1 = a/b, a1/b1
while d == d1 and x > 0:
yield int(d)
x -= 1
a,a1 = 10*(a % b), 10*(a1 % b1)
d,d1 = a/b, a1/b1
digits = [str(n) for n in list(pi_digits(DIGITS))]
print("%s.%s\n" % (digits.pop(0), "".join(digits)))
I tested both a few times against this online Pi digit generator.
All credit to this Gist by deeplook.
* Based on testing 10,000 digits, where I got about 7 seconds compared to about 1 second.
For up to 1 million digits of pi use math_pi (note: I am the author of the module)
Install with pip:
pip install math-pi
In Python:
>>> import math_pi
>>> print(math_pi.pi(b=1000))
3.1415926535...
From Fabrice Bellard site: Pi Computation algorithm. Sorry for such a straightforward implementation. 1000 is fast enough (0.1s for me), but 10000 isn't such fast - 71s :-(
import time
from decimal import Decimal, getcontext
def compute(n):
getcontext().prec = n
res = Decimal(0)
for i in range(n):
a = Decimal(1)/(16**i)
b = Decimal(4)/(8*i+1)
c = Decimal(2)/(8*i+4)
d = Decimal(1)/(8*i+5)
e = Decimal(1)/(8*i+6)
r = a*(b-c-d-e)
res += r
return res
if __name__ == "__main__":
t1 = time.time()
res = compute(1000)
dt = time.time()-t1
print(res)
print(dt)
I was solved with bellow formula 5-6 years ago.
Machin-like formula
Wikipedia: https://en.wikipedia.org/wiki/Machin-like_formula
Sorry for the code quality. Variable names can be meaningless.
#-*- coding: utf-8 -*-
# Author: Fatih Mert Doğancan
# Date: 02.12.2014
def arccot(x, u):
sum = ussu = u // x
n = 3
sign = -1
while 1:
ussu = ussu // (x*x)
term = ussu // n
if not term:
break
sum += sign * term
sign = -sign
n += 2
return sum
def pi(basamak):
u = 10**(basamak+10)
pi = 4 * (4*arccot(5,u) - arccot(239,u))
return pi // 10**10
if __name__ == "__main__":
print pi(1000) # 1000
I'm not familiar with your algorithm. Is it an implementation of BBP?
In any case, your make_pi is a generator. Try using it in a for loop:
for digit in make_pi():
print digit
Note that this loop is infinite: make_pi() never throws StopIteration
Here you can check whether your program outputs correct 1000 digits:
http://spoj.com/CONSTANT
Of course you can use diff or tc as well but you'd have to copy these 1000 digits from somewhere and there you just submit your program and check whether the score is bigger than 999.
You can try to print even more digits there and thus get more points. Perhaps you'd enjoy it.
Does this do what you want?
i = 0;
pi_str = ""
for x in make_pi():
pi_str += str(x)
i += 1
if i == 1001:
break
print "pi= %s.%s" % (pi_str[0],pi_str[1:])
Here is a different way I found here --> Python pi calculation? to approximate python based on the Chudnovsky brothers formula for generating Pi which I have sightly modified for my program.
def pifunction():
numberofdigits = int(input("please enter the number of digits of pi that you want to generate"))
getcontext().prec = numberofdigits
def calc(n):
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
k = 0
for k in range(n):
t = (Decimal(-1)**k)*(math.factorial(Decimal(6)*k))*(13591409+545140134*k)
deno = math.factorial(3*k)*(math.factorial(k)**Decimal(3))*(640320**(3*k))
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))
pi = 1/pi
return str(pi)
print(calc(1))
I hope this helps as you can generate any number of digits of pi that you wish to generate.
wallis formula can get to 3.141592661439964 but a more efficient way is needed to solve this problem.
https://www.youtube.com/watch?v=EZSiQv_G9HM
and now my code
x, y, summing = 2, 3, 4
for count in range (0,100000000):
summing *= (x/y)
x += 2
summing *= (x/y)
y += 2
print (summing)