How to create script that takes the "power" of an RNG function - python

I am attempting to make a script in Python/Jupyter Notebook(anaconda3).
the goal of the script is to flip a coin N(very large positive integer value) times.
i want it to track the results of the total flips, either all 1s, or not.
i need the function to do this for every column in a matrix parent matrix, which i am struggling to perform.
Any and all help is appreciated
originally i thought
N=C
F=secrets.randbelow(2)**C
would work, but this is just 1 or 0 to that power, and not
F=secrets.randbelow(2)*secrets.randbelow(2)secrets.randbelow(2)...
like im looking for
this is the crude code i have to tally and track the final value
Heads=0
Q=np.zeros(N)
for i in range(N):
Q[i]=secrets.randbelow(2)
print (Q)
for i in range(N):
if Q[i]==1:
Heads=Heads+1
if Heads==N:
print ('Verify')
else:
print('vote')
the issue is that i need this protocol to be performed every single time a new column of A is selected
ideally, it would be in a for loop that steps through A
for col in A:
coin flip matrix is determined and results calculated
if calculated value ==0:
else:

Related

How to use different columns for for loop iteration

So i want to do an iteration a vairable amount of times (a)
I have an excel sheet where that iteration is already programmed and i want to do the same now in python 3 spyder.
I decided to calculate the first row externally. The iteration should now look like this:
da,air core diameter (2,1) is has the input t_new (1,5), delta p, spray pressure (2,2) has input da,air core diameter (2,1), t_new (2,5) has the input delta p, spray pressure (2,2) and so on for a given number of iterations.
My code looks as follows up until now (everything else is defined properly beforehand):
a = [b for b in range(14)] # number of iterations -1
arr = np.array([[da_iter], [ps_iter], [t_mod_iter]]).reshape(1,3) # external calculated values first row
arr_zeros = np.zeros([len(a), 3]) # filling array with 0's based on iteration number
arr_iter = np.vstack((arr, arr_zeros)) #iteration array with 1st row calculated values
i = 0 #row index
j = 0 #column index
for i in range(len(arr_iter)):
np.append(arr_iter, do_in-2*arr_iter[i,j+2]) #calculating new da out of t_mod
np.append(arr_iter, ml**2*gs*0.5*pl*((dsc/(2*pl*(hsc*din*arr_iter[i+1,j]/2)))**2+(1/(pl*(ao-np.pi/4*arr_iter[i+1,j]**2)))**2)) #calculating new ps out of new da
np.append(arr_iter, k*(1738.7*ul**2-79.898*ul+2.0122)*((do_in*ml*ul)/(pl*arr_iter[i+1,j+1]))**0.25) #calculation new t_new out of spray pressure
i = i+1
print(arr_iter)
But that doesnt seem to work properly since i only get out arr_iter as it was before. Unfortunatley i also didnt found sth usefull how to iterate over changing rows using a for loop.
Does somebody have a better idea how to do it or sees my mistake in the loop?
Thank you very much in advance
First thing, you don't need i=i+1 as for loop already doing the same.
Secondly, I think you want to replace zeros in arr_iter so in for loop, you should write something like
np.append(arr_iter[i, j], 2nd_variable)
Alternatively you can simply do the following to update arr_iter matrix, rather than append.
arr_iter[i][j] = new_variable

Need Help Trying to Simplify this algorithm to map points on an arbitrarily large 2d plane to unique integers

So like the title says I need help trying to map points from a 2d plane to a number line in such a way that each point is associated with a unique positive integer. Put another way, I need a function f:ZxZ->Z+ and I need f to be injective. Additionally I need to to run in a reasonable time.
So the way I've though about doing this is to basically just count points, starting at (1,1) and spiraling outwards.
Below I've written some python code to do this for some point (i,j)
def plot_to_int(i,j):
a=max(i,j) #we want to find which "square" we are in
b=(a-1)^2 #we can start the count from the last square
J=abs(j)
I=abs(i)
if i>0 and j>0: #the first quadrant
#we start counting anticlockwise
if I>J:
b+=J
#we start from the edge and count up along j
else:
b+=J+(J-i)
#when we turn the corner, we add to the count, increasing as i decreases
elif i<0 and j>0: #the second quadrant
b+=2a-1 #the total count from the first quadrant
if J>I:
b+=I
else:
b+=I+(I-J)
elif i<0 and j<0: #the third quadrant
b+=(2a-1)2 #the count from the first two quadrants
if I>J:
b+=J
else:
b+=J+(J-I)
else:
b+=(2a-1)3
if J>I:
b+=I
else:
b+=I+(I-J)
return b
I'm pretty sure this works, but as you can see it quite a bulky function. I'm trying to think of some way to simplify this "spiral counting" logic. Or possibly if there's another counting method that is simpler to code that would work too.
Here's a half-baked idea:
For every point, calculate f = x + (y-y_min)/(y_max-y_min)
Find the smallest delta d between any given f_n and f_{n+1}. Multiply all the f values by 1/d so that all f values are at least 1 apart.
Take the floor() of all the f values.
This is sort of like a projection onto the x-axis, but it tries to spread out the values so that it preserves uniqueness.
UPDATE:
If you don't know all the data and will need to feed in new data in the future, maybe there's a way to hardcode an arbitrarily large or small constant for y_max and y_min in step 1, and an arbitrary delta d for step 2 according the boundaries of the data values you expect. Or a way to calculate values for these according to the limits of the floating point arithmetic.

How can select samples with apply method without replacing in a loop

I would like to select "dmin" numbers of samples in each group(group by) in a dataframe and add them to another empty dataframe.
If total number of samples which we need is not enough, again select new "dmin" numbers of samples and add to the dataframe. This loop needs to be repeated until total number of samples we need is covered.
I am new in coding and can not understand the problem, but samples are selected just one time in my code and can not be repeated time by time in a group.
Another problem is that in each group of that dataframe, the number of records might go to be less than value of "dmin" in the loop and the code might face this problem "number of samples in the group is less than "dmin".
I was wondering if you could help me. This is part of my code:
while V > 0:
x6 = result_sort[result_sort['K'] > p_ratio].groupby('position').apply(lambda x:x.sample(dmin).reset_index(drop=True))
A = x6.append(A)
S = len(A)
V = V_total - S
I solved my problem with adding another condition in while loop.

Searching a 3d array for the nearest "cell" that has a specific value - python

Please, Note that I am new to stack-overflow and may get some technicalities a bit wrong. If I do, please point them out
I have been writing a program that is intended to model how a disease (influenza) will spread though a population for my a-level NEA. A lot of it is built around a 3D array that represents many parts about a town with the 2 dimensions acting like a grid view (similar to chess or civilization 4 etc) and the 3rd storing information about the 2D cell (for example the first value per 2d cell is the population, second is the type of area, 3rd is the amount infected etc). Part of the code that represents the people moving from cell to cell, needs to know where the nearest 2D cell is that contains a certain value within the 3rd dimension of it. In practice this will essentially tell the computer where the nearest place for work/entertainment is.
For example in an array such as a 4 by 4 by 4 array, all with 0s except random 1s (I'm using integers in my program because they'll be more than 2 possibilities in final product), it will go though each 2D cell and find the nearest 1 in the second value in the 3rd dimension to the 2d cell it is currently on, store it in the array , then move to the next.
Here is my code so far:(everything before the subroutine will be different in final)
townLayout=[[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]]]
import random
b=0
while b<5:
i=0
while i<5:#double loop to create 2 dimentions
townLayout[b][i]=[0,ran.ranint(1,4),0,0,0,15,15,0,15,15,0]
i+=1
b+=1
def nearestWork(townLayout):#anitate
b=0
isThere=True
while b<5 and isThere==True:
i=0
xc=15
yc=15
dxc=15
dx=15
dyc=15
dy=15
while i<5 and isThere=True:
multiple=False
x=0
isThere=False
while x<5:
y=0
while y<5:
if townLayout[b][i][1]==4:
isThere=True
if xc>=b:
dxc=xc-b
else:
dxc=b-xc
if yc>=i:
dyc=yc-b
else:
dyc=b-yc
if x>=b:
dx=x-b
else:
dx=b-x
if y>=b:
dy=y-b
else:
dy=b-y
if (dx+dy)<(dxc+dyc):
xc=x
yc=y
elif (dx+dy)==(dxc+dyc):
Multiple=True
y+=1
x+=1
if isThere==True:
townLayout[b][i][8]=xc
townLayout[b][i][9]=yc
else:
print('no places of work detected')
break
if Multiple==True:
townLayout[b][i][10]=1
i+=1
b+=1
return townLayout
Is there a way to make this more efficient? will it work?

Making histogram out of matrix entries?

Today my task is to make a histogram to represent the operation of A^n where A is a matrix, but only for specific entries in the matrix.
For example, say I have a matrix where the rows sum to one. The first entry is some specific decimal number. However, if I raise that matrix to the 2nd power, that first entry becomes something else, and if I raise that matrix to the 3rd power, it changes again, etc - ad nauseum, and that's what I need to plot.
Right now my attempt is to create an empty list, and then use a for loop to add the entries that result from matrix multiplication to the list. However, all that it does is print the result from the final matrix multiplication into the list, rather than printing its value at each iteration.
Here's the specific bit of code that I'm talking about:
print("The intial probability matrix.")
print(tabulate(matrix))
baseprob = []
for i in range(1000):
matrix_n = numpy.linalg.matrix_power(matrix, s)
baseprob.append(matrix_n.item(0))
print(baseprob)
print("The final probability matrix.")
print(tabulate(matrix_n))
Here is the full code, as well as the output I got.
http://pastebin.com/EkfQX2Hu
Of course it only prints the final value, you are doing the same operation, matrix^s, 1000 times. You need to have s change each of those 1000 times.
If you want to calculate all values in location matrix(0) for matrix^i where i is each value from 1 to s (your final power) do:
baseprob = []
for i in range(1,s): #changed to do a range 1-s instead of 1000
#must use the loop variable here, not s (s is always the same)
matrix_n = numpy.linalg.matrix_power(matrix, i)
baseprob.append(matrix_n.item(0))
Then baseprob will hold matrix(0) for matrix^1, matrix^2, etc. all the way to matrix^s.

Categories

Resources