lundi 1 août 2016

Student: How to isolate and tally hit frequency within a np.random.choice range

Currently learning Python and very new to Numpy & Panda

I have pieced together a random generator with a range. It uses Numpy and I am unable to isolate each individual result to count the iterations within a range.

Goal: Count the iterations of "Random >= 1000" and then add 1 to the appropriate column that correlates to the tally of iterations. Example in very basic sense:

#Random generator begins... these are first four random generations
Randomiteration1 = 175994 (Random >= 1000)
Randomiteration2 = 1199 (Random >= 1000)
Randomiteration3 = 873399 (Random >= 1000)
Randomiteration4 = 322 (Random < 1000)

#used to +1 to the fourth row of column A in CSV
finalIterationTally = 4

#total times random < 1000 throughout entire session. Placed in cell B1
hits = 1

(The logic would then be to +1 to A4 in the spreadsheet. If the iteration tally would have been 7, then +1 to the 7th column, etc. So essentially, I am measuring the distance and frequency of that distance between each "Hit")

My current code includes a CSV export portion. I do not need to export each individual random result any longer. I only need to export the frequency of each iteration distance between each hit. This is where I am stumped.

Cheers

import pandas as pd
import numpy as np

#set random generation quantity
generations=int(input("How many generations?\n###:"))

#random range and generator
choices = range(1, 100000)
samples = np.random.choice(choices, size=generations)

#create new column in excel
my_break = 1000000
if generations > my_break:
    n_empty = my_break - generations % my_break
    samples = np.append(samples, [np.nan] * n_empty).reshape((-1, my_break)).T

#export results to CSV
(pd.DataFrame(samples)
 .to_csv('eval_test.csv', index=False, header=False))

#left uncommented if wanting to test 10 generations or so
print (samples)




Generate a randon matrix in MATLAB with equal number of values less than 0.5 and greater than 0.5.

I want to generate a random matrix of size n such that it has equal number of elements less than 0.5 and greater than 0.5.

Sorry if it sounds trivial but any help would be appreciated.

Thanks




How to generate a random alphanumeric string of a custom length in java?

What is the most simple way? Minimizing any imports.

This one is good:

String str = Long.toHexString(Double.doubleToLongBits(Math.random()));

But it's not perfect, for example it complicates with custom length.




Randomised Image in array is displaying wronged for image tag

functionality:

I have set 2 image tags in my html body to be displaying 2 randomised images from an array. Secondly, I have ensured that the 2 displayed randomised images will not repeat itself via the code line var Brand = BrandNameArray.splice(random_BrandIndex, 1)[0];

However, when I do run the code, I have noticed that the second image for the 2nd image tag in the html body is displaying the wrong image. It is displaying an image index of +1.

Meaning:

I have an array_Image = [A, B, C, D, E] and within my console log, it is stated that the randomised image returns 2 images of [0,3], hence rightfully, it should be showing image [A , D] in my image tag of my html body. However, the images that are displayed are [A, E]. The following behaviour has occured quite a number of times even though, it is not consistent.

Could i please get some help on this. Thanks.

I have attached the following code for your perusal.

The following code of onclick="selectBrand('2'); is called when user clicks on the displayed randomised generated image, will display a popup image that is also from another array that is appended to Brand_list.push(random_BrandIndex);, depending on the image that is being pushed to the temporary store array -> var Brand_List=[];

 //Brand Offers
 var Brand_list = [];

 var BrandNameArray = ["lib/img/Brands/Anderson.png", "lib/img/Brands/ChalkFarm.png", "lib/img/Brands/ChickenUp.png", "lib/img/Brands/FishMartSakuraya.png", "lib/img/Brands/HoneyWorld.png"];






 //Randomised Brand Offer
 //Auto populate into brand container once randomised
 $('#BrandWinlist > img').each(function(i, img) {

   random_BrandIndex = Math.floor(Math.random() * BrandNameArray.length);
   console.log("random_BrandIndex:" + random_BrandIndex);

   //Assign Variable to generate random Brands
   //var Brand = BrandNameArray[random_BrandIndex];
   console.log("Brand:" + Brand);


   var Brand = BrandNameArray.splice(random_BrandIndex, 1)[0];

   Brand_list.push(random_BrandIndex);

   $(img).attr('src', Brand).show();
 });

 console.log("Brand_list:" + "[" + Brand_list + "]");
<div id="MainBackground" align="center" style="position:absolute; width:1080px; height:1920px; background-repeat: no-repeat; z-index=8; top:0px; left:0px; margin:auto;">


  <!--Div to show my 2 randomised images-->
  <div class="GameWinBrand_Container">
    <div id="BrandWinlist" class="GameWinBrand_innerScroll">
      <img id="GameBrand_1" style="width:230px; height:230px; top:0px; left:0px; border:0px; outline:0px" onclick="selectBrand('1');">
      <img id="GameBrand_2" style="width:230px; height:230px; top:0px; left:330px; border:0px;" onclick="selectBrand('2');">
    </div>
  </div>


</div>



Optimising the generation of a large number of random numbers using python 3

I am wanting to generate eight random numbers within a range (0 to pi/8), add them together, take the sine of this sum, and after doing this N times, take the mean result. After scaling this up I get the correct answer, but it is too slow for N > 10^6, especially when I am averaging over N trials n_t = 25 more times! I am currently getting this code to run in around 12 seconds for N = 10^5, meaning that it will take 20 minutes for N = 10^7, which doesn't seem optimal (it may be, I don't know!).

My code is as follows:

import random
import datetime
from numpy import pi
from numpy import sin
import numpy
t1 = datetime.datetime.now()

def trial (N):
    total = []
    uniform = numpy.random.uniform
    append = total.append
    for j in range (N):
        sum = 0
        for i in range (8):
            sum+= uniform(0, pi/8)
        append(sin(sum))
    return total

N = 1000000
n_t = 25
total_squared = 0
ans = []
for k in range (n_t):
    total = trial(N)
    f_mean = (numpy.sum(total))/N
    ans.append(f_mean*((pi/8)**8)*1000000)
sum_square = 0
for e in ans:
    sum_square += e**2
sum = numpy.sum(ans)
mean = sum/n_t
variance = sum_square/n_t - mean**2
s_d = variance**0.5
print (mean, " ± ", s_d)
t2 = datetime.datetime.now()
print ("Execution time: %s" % (t2-t1))

If anyone can help me optimise this it would be much appreciated!

Thank you :)




Better way of generating unpredictable, short alphanumeric id for database entries

I'm working on a yellow pages site that has around 1 million entries. I'm currently using random md5 hash as id but think its a bad idea (being longer, consumes more space).

Is there any nicer way of generating an unpredictable, random, short alphanumeric id in PHP other than using uniqid() function. I'm not using auto-increment ids, base64 etc since data scraping would be very easy.




Random factor for simulating a Poisson distribution with a tick-tick simulation

I've got a program that simulates events happening. I have the following constraints:

  • The distribution should approximate a Poisson distribution, i.e., independent events occurring at a fixed rate.
  • At time 1000 ticks, the event should have happened 100 times (on average). (1000 and 100 are placeholders; the real numbers are determined experimentally from the real-world system I'm trying to model.)

I'm currently using code of the following form:

def tick():
    doMaintenance()
    while random() < 0.1:
        eventHappens()

I use a while instead of an if to simulate the idea that these events are independent. Otherwise, there would be no chance of two events occurring in the same tick. However, I suspect that means that the random() < 0.1 (where random returns a number in the half-open range [0.0, 1.0)) is slightly inaccurate. (It's okay that I'm quantizing the event occurrence time.)

Can somebody suggest the correct random() < f constant to use if I want (in the general case) a Poisson distribution such that at time t there will be event count e? I believe that such a constant f exists, but its derivation is not obvious to me.

I'm putting this in stackoverflow.com so I can conveniently talk in coding terms and because I'm using a tick-tick simulation which is more familiar to numerical simulation programmers than mathematicians. If this is something more appropriate in math.stackexchange.com, though, let me know.