mardi 30 avril 2019

what's wrong with runif (or maybe me) in R?

I am trying to generate a random variable fron uniform distribution that also depends on random variable.

Ideally, I want z2 to be a random variable as well.

For example,

set.seed(123)
#generate first random variable z1
z1 <- runif(10,0,1)
#generate secondrandom variable z2
z2 <- ifelse(z1>= 0.7, runif(1,0.6,0.9), runif(1,0.2,0.5))
df <- data.frame(z1,z2)

But if you look at z2 it contains only two levels.

          z1        z2
1  0.2875775 0.3360002
2  0.7883051 0.8870500
3  0.4089769 0.3360002
4  0.8830174 0.8870500
5  0.9404673 0.8870500
6  0.0455565 0.3360002
7  0.5281055 0.3360002
8  0.8924190 0.8870500
9  0.5514350 0.3360002
10 0.4566147 0.3360002

We can generate 1000 number and summarize the results.

set.seed(123)
#generate first random variable z1
z1 <- runif(1000,0,1)
#generate secondrandom variable z2
z2 <- ifelse(z1>= 0.7, runif(1,0.6,0.9), runif(1,0.2,0.5))

table(df$z2)

0.352099318057299 0.655542095610872 
              707               293








i need help in doing python lab! I dont know how to do it. someone please help me! thank you

In this lab, you will print the user's "fortune".

Create a python program named fortune.py. In the program:

create a list (array) called fortuneList containing the following elements: "You will have great luck!" "You will have bad luck" "You will have average luck" select a random integer from 0 to the length of the fortuneList (see previous code samples that chose a random integer) print the fortune from the fortuneList with the subscript matching the randomly-selected integer

Submit the complete fortune.py file.




Randomly sampling from large combination generator

At a high level, I'm trying to sample n_samples items across all combinations of n items from a list. At small values of n and relatively small list lengths (n <= 5, len(list) < 75) this is fine - I just use itertools to generate combinations, convert to a list, and randomly sample the correct number using random.sample.

However, my use case requires that I generate the combinations, randomly sample several thousand elements, and then remove one of the combinations from the list and start again with the smaller list.

This creates a problem at high values of n and the len(list) - with 120 list items and n = 5, this usecase means that I have to do list conversion many times and I thus become time constrained by generator --> list conversion for a generator with ~190 million items. This takes an extremely long time (in excess of 20 minutes for especially bad examples).

The usecase doesn't require statistically uniform samples or anything, and I am purely using sampling because with high n and long lists processing every possible combination is computationally impractical and fast processing is extremely important.

I switched to using the iterator.islice method to only take the first n_samples items from the generator and use those. That dramatically increases speed (the example which took 20 minutes now takes 34 seconds), but performance is taking a hit. I think this is due to how itertools generates combinations - as an example,

list(itertools.combinations(list(range(4)), 2))

produces this list: [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

so it seems that if I have a long enough list and a large enough n, sampling even 100,000+ items by just pulling them off the generator will result in 100,000+ items where the first element is the same which is not ideal. As I said, I don't need perfect random sampling, but I think my performance crash from using this method instead of randomly sampling across the whole list is due to this.

Basically, I need a good way to efficiently sample n_samples items (where n_samples is somewhere from 10k to 500k) from all possible combinations of length n (where n is typically in a range of around 2-8) from a list of length which can vary from ~20 to ~200.

Thanks so much for any advice or resources you can provide!




How to randomly select HEX colors in MySQL but avoid a specific color range?

THE BACKGROUND

I am using a MySQL database to store data which I retrieve in data visualization on my website. Two out of ~800 items are of main interest in my visualization and will have a specific color code assigned to them (dark and light orange) inside a bar chart. Filters are used for the visualization, so each time a different set of items could be visible, but the 2 main items should always stick out (if existent after the filter).

DESIRED SOLUTION

I want to achieve both

  • A colorful bar chart
  • easy visual recognition of the two main items by avoiding similar colors in the chart

MY CURRENT SOLUTIONS

One way might be to just create a random set of hex colors, manually (or semi-automatically) change all colors of items that have a similar color code to those of the two main items and store it as a list to be retrieved. And for now, that would be my strategy...

But I would really like to have an automated way which would just create random hex codes, but avoid a specific color range (in my case everything orange).

I know already how to randomly create a hex code:

concat('#',SUBSTRING((lpad(hex(round(rand() * 10000000)),6,0))

Now the next step would be the avoidance of the orange color scheme.

MY QUESTION

Any ideas on how to achieve this inside a SELECT statement?

SELECT
   item,
   concat('#',SUBSTRING((lpad(hex(round(rand() * 10000000)),6,0)) as color --THIS SHOULD CHANGE
   FROM item_list




My Math.random is not so random. Any ideas how to make it more random? [on hold]

I am trying to make a guessing game where the computer generates a random number and you guess it. The problem is, anytime it makes a "random number," it generates a 1, 9, or 10. I keep testing this and it only gives me one of those three values. What should I do to make this more random?

Math.floor(Math.random() * 10) + 1;

I want it to have it more randomized and have a 3, 6, 4 or other number some times, not just a 1, 9, or 10.

var hiddenNumber = Math.floor(Math.random() * 10) + 1;

function guessFunction() {
  var input1 = document.getElementById("input1").value;
  if (input1 == hiddenNumber) {
    alert("Great Job!");
  } else if (input1 > hiddenNumber) {
    alert("Your Number Is Too High. Go Lower!");
  } else {
    alert("Your Number Is Too Low. Go Higher!");
  }
}

document.getElementById("enterButton").addEventListener("click", guessFunction);




How to generate random coordinates between two straights?

I have a vector with fixed coordinates, and given an increase in the Y axis (down and up) that determines me a region, I need to calculate random coordinates.Image by the vector (black) coordinates and random coordinates (blue)

I can generate a function to determinate the straights between the region i need to work. But i dont know how to generate random coordinates that belong to the region i need.

I'm looking for ideas for how to implement it.




Get random entities (including children) using NewGuide() in .Net Core 2

I needed to get some random entities from database, using EF Core, including some children entities. First, I used this example :

var entities = await context.Entities
    .Include(p => p.Children1)
    .Include(p => p.Children2)
    .Include(p => p.Children3)
    .OrderBy(p => Guid.NewGuide())
    .Take(4)
    .ToListAsync();

The problem for this using is that Guid.NewGuide() return children randomly, and is not assigned only for main entities. So, sometimes I get Children1, sometimes not, and I need to apply this random interogation only for the main.

I find a solution, but I think is not the best, and need to know if exist another better. First time, I get the ids for some random main entities, then I get all there entities including children (this is bad because I do 2 request into database):

var ids = context.Entities
    .OrderBy(p => Guid.NewGuid())
    .Take(4)
    .ToListAsync();

var entities = context.Entities
    .Include(p => p.Children1)
    .Include(p => p.Children2)
    .Include(p => p.Children3)
    .Where(p => ids.Contains(p.Id)
    .ToListAsync();




How to randomly select x number of indices from a matrix in Matlab

I'm trying to generate a randomly scattered but limited number of 1's in a matrix of zeros efficiently.

Say I have a 10x10 matrix of zeros (zeros(10)) and I want to randomly place ten 1's so it looks like:

     0     0     0     0     0     0     0     0     0     1
     0     0     0     0     0     1     0     0     0     0
     0     0     1     0     0     0     0     0     0     0
     0     0     0     0     0     0     0     0     1     0
     1     0     0     0     0     1     0     0     0     0
     0     0     0     0     0     0     0     0     0     0
     0     0     0     1     0     0     0     0     0     0
     0     1     0     0     0     0     0     1     0     0
     0     0     0     0     1     0     0     0     0     0
     0     0     1     0     0     0     0     0     0     0

How can I do this WITHOUT a for-loop and without manually plugging in each position (this example is a much smaller version of my real problem)?

My code so far:

% Generate zeros
M = zeros(10)
% Generate random indices
Rands = [randsample(10, 10) randsample(10, 10)]

Where the first column is intended to be the row indices and the second column the column indices.

Now I obviously can't just drop these indices into the row and column indices of M like this:

M(Rands(:,1), Rands(:,2)) = 1

How can I vecorise the changes to these random indices?




How do I generate a random number, put them into dictionary and then give back the count of repetitions

I have the task to create a function that is calculating a random number, which is then added into a dictionary until a this number is randomly generated again. As a result the number of repetitions has to be printed into the console.

I have already tried the following but I do not get results. I am a Python beginner so I also feel a bit lost.

import random

def repetition(a, b):
d = dict()
x = random.randint(a ,b)
for i in d:
    if x in d.values:
        return len(dict)
    else:        
        dict.update(x)

In the last step the results should be formated as a tuple of the generated numbers and then last but not least the number of repetitions which might look like this:

repetition(2, 5255)
([1244, 2415, ... ], 122)




lundi 29 avril 2019

Random number generation using Java 8

I'm working on Java 8 code to generate one time passwords (random). Below are the security requirements:

Following are the approved PRNG mechanisms:
· HASH_DRBG
· HMAC_DRBG
· CTR_DRBG#

I know that Java 9 SecureRandom supports these mechanisms, but how about Java 8? Anyway to achieve this using Java 8 code?

Thanks a lot,
Raj




How do I share the random number generator in numpy c-api

I wrote a Python program that call random functions from bothnumpy (e.g., np.random.normal) and also used some c++ functions which I compile and call using the standard numpy c-api. How can I make sure that all the functions use the same pseudo random number generator?




Is there a way for creating pseudo random bits using a seed of limited number of random bits? [on hold]

I need a way to create a large amount of pseudo random bits given a seed of random bits (deterministic way like PRG so seed1=seed2 => rand1=rand2). I have seen SHA functions but they return strings . I would like to get help. Thanks.




Why is random.choice so imbalanced?

So I have been writing some very random experimental code, and I found the results I got kind of puzzling.

This is my code

from random import choice

class A:


    def __init__(self, l):
        parsed = iter(l)

        self.include = next(parsed) == "+"
        self.l = list(parsed)



    def get(self, l):
        rt = self.l
        if self.include:
            rt += l
        return choice(rt)



a = A("+abcd")

d = dict()
for key in "abcdef":
    d[key] = 0

for i in range(100000):
    d[a.get(["e", "f"])] += 1

print(d)

I expected that code to output a random but somewhat even distribution of choices. Something like this:

{'a': 16678, 'b': 16539, 'c': 16759, 'd': 16584, 'e': 16631, 'f': 16809}

But the actual output is this:

{'a': 3, 'b': 4, 'c': 7, 'd': 3, 'e': 49588, 'f': 50395}

I mean, it is random, but if that was for real I might as well have won the lottery 10 times by now.

So, what exactly is going on here? Why does the random.choice function prefer to choose "e" and "f" so much over the others?




POSTGRESQL random() gives always the same value for the whole table. How to fix it?

I want to build a sql that generates a 2 column table where the first are series of timestamps and the second is a functon that provides values. For example here is random(). But the random function give me always the same value for the whole table, I want different. How to fix it?

SELECT * FROM generate_series('2008-03-01 00:00'::timestamp,
                              '2008-03-05 12:00',
                              '1 day') as ts, random() as value;

Generated table:

"2008-03-01 00:00:00";0.816707271616906
"2008-03-02 00:00:00";0.816707271616906
"2008-03-03 00:00:00";0.816707271616906
"2008-03-04 00:00:00";0.816707271616906
"2008-03-05 00:00:00";0.816707271616906




dimanche 28 avril 2019

how to get loop JSON value amount with random value array use PHP

{
  "success": 1,
  "return": {
    "1400151861513776": {
      "pair": "edc_btc",
      "type": "buy",
      "amount": 138959.22155687,
      "rate": 0.00000085,
      "timestamp_created": "1556464987",
      "status": 0
    },
    "1400151861456538": {
      "pair": "edc_btc",
      "type": "buy",
      "amount": 4115.53246448,
      "rate": 0.00000085,
      "timestamp_created": "1556463520",
      "status": 0
    },
    "1400151861402138": {
      "pair": "edc_btc",
      "type": "buy",
      "amount": 252.29423504,
      "rate": 0.00000085,
      "timestamp_created": "1556462106",
      "status": 0
    },
    "1400151861205651": {
      "pair": "edc_btc",
      "type": "buy",
      "amount": 5735.02289537,
      "rate": 0.00000085,
      "timestamp_created": "1556457111",
      "status": 0
    },
    "1400151861064946": {
      "pair": "edc_btc",
      "type": "buy",
      "amount": 608.2294235,
      "rate": 0.00000085,
      "timestamp_created": "1556453555",
      "status": 0
    },
    "1400151860984352": {
      "pair": "edc_btc",
      "type": "buy",
      "amount": 13553.51532229,
      "rate": 0.00000085,
      "timestamp_created": "1556451515",
      "status": 0
    },
    "1400151860967764": {
      "pair": "edc_btc",
      "type": "buy",
      "amount": 49475.62404601,
      "rate": 0.00000085,
      "timestamp_created": "1556451103",
      "status": 0
    },
    "1400151860901030": {
      "pair": "edc_btc",
      "type": "buy",
      "amount": 21474.82564282,
      "rate": 0.00000085,
      "timestamp_created": "1556449399",
      "status": 0
    },
    "1400151860889146": {
      "pair": "edc_btc",
      "type": "buy",
      "amount": 2657.50733826,
      "rate": 0.00000085,
      "timestamp_created": "1556449090",
      "status": 0
    },
    "1400151860484795": {
      "pair": "edc_btc",
      "type": "buy",
      "amount": 71933.21911691,
      "rate": 0.00000085,
      "timestamp_created": "1556438570",
      "status": 0
    },
    "2400151859280443": {
      "pair": "edc_btc",
      "type": "sell",
      "amount": 266054.68380596,
      "rate": 0.00000088,
      "timestamp_created": "1556408217",
      "status": 0
    },
    "2400151857916444": {
      "pair": "edc_btc",
      "type": "sell",
      "amount": 400000,
      "rate": 0.0000009,
      "timestamp_created": "1556374931",
      "status": 0
    },
    "2400151857916059": {
      "pair": "edc_btc",
      "type": "sell",
      "amount": 400000,
      "rate": 0.00000089,
      "timestamp_created": "1556374923",
      "status": 0
    }
  }
}

how to get loop value amount..this array has random value 1400151861513776..change everytime..

i use php code.. json_decode..




How to generate random numbers with given length of input to add and multiply

I'm trying to generate 2 lists of random numbers between 1 to 10 and trying to do an user input for how many numbers they want to generate per list. Then I'm trying to figure out how to add and multiply the 2 lists together.

The problem is that I feel like I know how to make all this happen separately but I can't seem to figure out how to put them together using main()

for example : i import random then create a blank list for the random generator to put numbers into the empty list, but I don't know how to create an easy way for the user input the number in for the length of the list.

import random

myList = []

for i in range(1,11):
    x = random.randint(1, 10)
    myList.append(x)


print(myList)

input("Amount of numbers preferred in a list: ")   <---- not sure where to put this and add more code to be part of the generating process.




HOW CAN I WRITE TEXT OF RANDOM LINE STRING IN MULTILINE EDIT TEXT AT KOTLIN?

I WRITE SOME STRING IN MULTILINE EDIT TEXT AT KOTLIN.I WANT TO WRITE RANDOM STRING LINE WHEN I PRESS SAVE BUTTON.HOW CAN I FIND RANDOM LINE İN EDIT TEXT AT KOTLIN?




Random Index from a Tensor (Sampling with Replacement from a Tensor)

I'm trying to manipulate individual weights of different neural nets to see how their performance degrades. As part of these experiments, I'm required to sample randomly from their weight tensors, which I've come to understand as sampling with replacement (in the statistical sense). However, since it's high-dimensional, I've been stumped by how to do this in a fair manner. Here are the approaches and research I've put into considering this problem:

  • This was previously implemented by selecting a random layer and then selecting a random weight in that layer (ignore the implementation of picking a random weight). Since layers are different sizes, we discovered that weights were being sampled unevenly.

  • I considered what would happen if we sampled according to the numpy.shape of the tensor; however, I realize now that this encounters the same problem as above.

    Consider what happens to a rank 2 tensor like this:

    [[*, *, *],
     [*, *, *, *]]
    
    

    Selecting a row randomly and then a value from that row results in an unfair selection. This method could work if you're able to assert that this scenario never occurs, but it's far from a general solution.

    Note that this possible duplicate actually implements it in this fashion.

  • I found people suggesting flattening the tensor and use numpy.random.choice to select randomly from a 1D array. That's a simple solution, except I have no idea how to invert the flattened tensor back into its original shape. Further, flattening millions of weights would be a somewhat slow implementation.

  • I found someone discussing tf.random.multinomial here, but I don't understand enough of it to know whether it's applicable or not.

  • I ran into this paper about resevoir sampling, but again, it went over my head.

  • I found another paper which specifically discusses tensors and sampling techniques, but it went even further over my head.


Any help understanding how to do this? I'm working in Python with Keras, but I'll take an algorithm in any form that it exists. Thank you in advance.




How to get a specific number from a list?

I want to randomize the words in the list and if the randomized word equals to scissor I want the game to tell me that I've won but I cant find the solution, could you tell me where I done wrong?

I have tried "if 3 in my_list:" but still can't find the solution

import random

my_list = ["rock", "paper", "scissor"]
random.choice(my_list)
print(random.choice(my_list))

if random.choice(my_list) == my_list[3]:
    print("You Won!")
else:
    print("You Lost!")

I want to print "You Won" when the random.choice is scissors in the list.




rand() function behavior

I'm learning about the rand() function in C, as I want to use it to generate a random number in a range. However, I have a question about a part of the algorithm below.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    const MAX = 20, MIN = 1;
    srand(time(NULL));
    int randNumber = rand() % (MAX - MIN + 1) + MIN;
    printf("%d", randNumber);
    // yeu cau nhap so
    int duDoan;
    printf("Moi ban du doan con so:");
    scanf("%d", &duDoan);
    // chay vong lap kiem tra
    while(duDoan != randNumber) {
        printf("Ban da sai. Moi nhap lai:");
        scanf("%d", &duDoan);
    }
    printf("Ban da nhap dung. Dap an la: %d ", randNumber);

    return 0;
}

What confuses me here is why we have to add + MIN in this line:

rand() % (MAX - MIN + 1) + MIN;

If I leave it, what will the result be?




short way of producing array of randomly draw strings by RandomStringUtils

I would like to produce an array of randomly creating strings in a short way. There is such a way in case ints (instead of strings), so I'm searching for something similar using org.apache.commons.lang3.RandomStringUtils instead of java.util.Random.

I've tried to search through methods for RandomStringUtils, but I didn't found anything useful.

The simple code producing an array of 13 pieces of ints is as follows:

java.util.Random r = new java.util.Random();
int[] toReturn = r.ints(0,100).limit(13).toArray();

Is it possible to find something analogous for RandomStringUtils?




Generate list of random numbers starting with x

so I was asked to generate a list of random numbers from 1 to 100. Then I was asked to print a message at each random number that was divisible by 7, that was okay too.

So now my issue is that this list has to start with the number 1 and has then to be continued with random numbers. Addiotionally, I wand to print a certain text every fifth line.

Questions: 1) How do I start my list with the number 1 and still keep the rest random? 2) How do I print a message every fifth line?

Best regards, Djabone

I have been searching for 2 hours and only found results for python and other languages. I was not able to find the right answer.

import java.util.Random;

public class rannumb {

public static void main(String[] args) {

    Random rnd = new Random();
    int number;

    for(int i = 1; i<=100; i++) {
        if (i%7==0) {
            System.out.println(i+ " : Lucky number!");
        }

        number = rnd.nextInt(100);
        System.out.println(number); 

    }
}

}

The output I get is :

  • 3, 69, 75, 83, 96, 47, 7 : Lucky number!, 56, 30, 98, 6, 66, 97, 63, 14 : Lucky number!

The output I expect to get is:

  • 1, 3, 69, 75, 83 : message, 96, 47, 7 : Lucky number!, 56, 30 : message, 98, 6, 66, 97, 63, 14 : Lucky number!



samedi 27 avril 2019

Fast way to generate samples with np.random.choice()?

I want to generate random sample without replacement for N times, like following:

import numpy as np

sample = np.zeros([100000, 4], int)
for i in range(100000):
    sample[i] = np.random.choice(128, 4, replace=False)

If the iterations become very large, the overall sampling will be time consuming. Is there any way to speed up this sampling?




vendredi 26 avril 2019

How to sort counted(occurrence) numbers in increasing order?

I have given this question to create 50 random numbers from 1 to 15 and count how many times each occurred. I need to print them out in increasing order, but I couldn't. So far, I can only print out the numbers randomly and counter increasingly next to them. Any idea how I can print them out in order?

Thank you

INCLUDE Irvine32.inc
.data
blank byte " ",0

count byte 16 dup (0)
    dates dword 50 dup (?)
.code
main PROC 
call randomize
mov edx, offset blank
    mov edi,0   ;count index
mov ecx,50 
printnum:

    mov eax,15
    call randomRange    
    add eax,1
    call writedec
        mov dates[edi],eax;

        add edi,4;
    mov esi, eax
    inc count[esi]
        call writestring
        movzx eax,count[esi]
        call writedec
    call writestring
        mov eax,ecx

loop printnum

call crlf 

exit
main ENDP
end main




Simulate left Truncated Gamma distribution with mean = 1 and variance =0.4

Suppose $X$~Gamma$\left(\alpha, \beta\right)$, I would like to truncate all values of $X

MATLAB codes:

t = 0.5;  theta = 0.4; 
syms alpha beta 
EX = beta*( igamma(alpha+1,t/beta) /  igamma(alpha,t/beta) ); %Mean  
EX2 = beta^2*( igamma(alpha+2,t/beta) /  igamma(alpha,t/beta) );%Second moment         
VarX = EX2 -EX^2; %Variance       
cond1 = alpha > 0; cond2 = beta > 0; cond3 = EX==1; cond4 = VarX ==theta;
conds =[cond1 cond2 cond3 cond4]; vars = [alpha, beta];
sol = solve(conds, [alpha beta], 'ReturnConditions',true);
soln_alpha = vpa(sol.alpha)
soln_beta = vpa(sol.beta)

The above code returns a numeric answer only if the constraint that $\alpha>0$ is relaxed. The numeric answer has a negative value of $\alpha$ which is wrong since both $\alpha$ (shape parameter) and $\beta$ (scale parameter) must be strictly positive.




Create new column filled with random elements based on a categorical column

I have a pandas dataframe that looks like this:

ID  Cat
87    A 
56    A 
67    A  
76    D  
36    D 

Column ID has unique integers, while Cat contains categorical variables. Now I would like to add two new columns with conditions about Cat.

The desirable result should look like this:

ID  Cat  New1   New2
87    A    67    36
56    A    67    76
67    A    56    36
76    D    36    56
36    D    76    67

Column New1: for each row, pick a random ID with the SAME category as the current row ID, with replacements.

Column New2: for each row, pick a random ID with a DIFFERENT category than the current row ID, with replacements.

How can I do this efficiently?




Why is Int.random() ruining slower than arc4random_uniform()?

I have used Int.random() method and arc4random_uniform() for number generation speed tests.
Both tests were run in macOS console with build configuration set to release. Below are codes which I have used for testing.

public func randomGen1() {
    let n = 1_000_000
    let startTime = CFAbsoluteTimeGetCurrent()
    for i in 0..<n {
        _ = arc4random_uniform(10)
    }
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print(timeElapsed)
}
public func randomGen2() {
    let n = 1_000_000
    let startTime = CFAbsoluteTimeGetCurrent()
    for i in 0..<n {
        _ = Int.random(in: 0..<10)
    }
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print(timeElapsed)
}

The times I got are
0.029475092887878418 (for arc4random_uniform(10))
0.20298802852630615 (for Int.random(in: 0..<10))

Why is Int.random() so much slower?
Is there a way to optimise it?
Are there any faster methods for random number generation in swift?




Functional way to generate file names in Scala

Ok, I want to generate temp file names. So, I created a class with var tempFileName and fileNo such that it creates files like

BSirCN_0.txt
BSirCN_1.txt
BSirCN_2.txt

But, to do this I have to keep count and the way I am going it is calling next() function of the class which returns the filename in sequence (should return BSirCN_4 in the above case. Now this goes against FP as I am modifying the state i.e. the count of names in the Object. How do I do it in a functional way. One way I can think of is keeping count where the function is called and just concatenate. Any other ways?




Random generator creates the same numbers

While looping through a for loop which is randomly 1-10 long. I also go through a while loop. I am trying to find 6 random numbers between 1-42. I then do that again (1-10) times. Currently, these 6 random numbers stay the same. I suspect it has something to do with the seed but I could not solve it.

I tried to use both SecureRandom, Random, and via Math.random() Nothing has worked.

    private Random random = new Random();

    private int getRandomInt(int min, int max) {
         return random.nextInt((max - min) + 1) + min;
    }

    public ArrayList<LottoTip> createOpponentTips() {
        ArrayList<Integer> opponentChosenNumbers = new ArrayList<>();
        ArrayList<LottoTip> lottoTips = new ArrayList<>();

        //1-10
        int amountOfTips = getRandomInt(MIN_TIPS, MAX_TIPS);

        for (int i = 0; i < amountOfTips; i++) {

            int[] arrayOpponentChosenNumbers = new int[REQUIRED_NUMBERS];

            while (opponentChosenNumbers.size() < REQUIRED_NUMBERS) {

                //1-42 This here is the problem zone

                int randomNumber = getRandomInt(RANGE_NUMBER_MIN, RANGE_NUMBER_MAX);
                if (!opponentChosenNumbers.contains(randomNumber)) {
                    opponentChosenNumbers.add(randomNumber);
                }
            }
            //1-6 ---This here works
            int opponentLuckyNumber = getRandomInt(RANGE_LUCKY_NUMBER_MIN, RANGE_LUCKY_NUMBER_MAX);

            for (int j = 0; j < opponentChosenNumbers.size(); j++) {
                arrayOpponentChosenNumbers[j] = opponentChosenNumbers.get(j);
            }

            lottoTips.add(new LottoTip(arrayOpponentChosenNumbers, opponentLuckyNumber));
        }

        return lottoTips;
    }


Here is a System.out.println as you can see the Numbers are staying the same. Could you help me find a way to create a getRandomInt method which works all the time?

Thank you very much for your help.

Kerry York [
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 2, 
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 4, 
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 5, 
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 1, 
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 3, 
Numbers: 6, 4, 30, 15, 25, 5 Lucky Number: 6]

Don Dickinson [
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 6, 
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 5, 
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 3, 
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 2, 
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 4, 
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 1, 
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 1, 
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 4, 
Numbers: 23, 29, 34, 18, 16, 19 Lucky Number: 3]

Clifford Weinstein [
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 6, 
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 3, 
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 2, 
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 1, 
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 4, 
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 3, 
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 5, 
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 6, 
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 3, 
Numbers: 6, 33, 13, 2, 37, 38 Lucky Number: 3]

Angela Spencer [
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 6, 
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 3, 
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 2, 
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 4, 
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 5, 
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 4, 
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 2, 
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 2, 
Numbers: 12, 39, 8, 25, 40, 15 Lucky Number: 3]

Leroy McIntosh [
Numbers: 5, 23, 2, 24, 28, 3 Lucky Number: 1]




Generate a specific number of ones for each row, but only where x = zeroes

Suppose I have an array like

0 1 1 1 0 0 0 0 1 0

0 0 1 0 0 1 0 0 0 0

1 0 0 0 0 1 0 0 1 0

I want each row to have a specific number of ones- let's say, 5 ones per row. So in the first row I need to add 1 one, second row needs 3 ones, and the third needs 2. I need to randomly generate those ones in places where x = 0.

How do I do this?




How to split a set of strings into substrings in Python, making shorter substrings more likely?

I have a set of strings which are some millions of characters each. I want to split them into substrings of random length, and this I can do with no particular issue.

However, my question is: how can I apply some sort of weight to the substring length choice? My code runs in python3, so I would like to find a pythonic solution. In detail, my aim is to:

  • split the strings into substrings that range in length between 1*e04 and 8*e06 characters.
  • make it so, that the script chooses more often a short length (1*e04) over a long length (8*e06) for the newly generated substrings, like a descending length likelihood gradient.

Thanks for the help!




jeudi 25 avril 2019

Hidden Markov Model not working properly, unknown logic/syntax error in MATLAB code

I have created this code from scratch. I want to make a plot and/or histogram of my "Observed" and "State" (these are 2 matrices). Some problem occurs at the 200th iteration, where my State matrix just becomes all 0's, there is no data being input into the State matrix. Can anyone troubleshoot the code? My possible states are {1,2,3}. The error might be occurring at the line:

State(k) = randsample(N, 1, true, A(State(k-1),:));

BUT, maybe there are incorrect subtleties throughout code I am unaware of. MATLAB and HMM are very new to me. Thank you!

%Initialize A,pi,T

N = 3; # of states
%A is transition prob matrix
A = [.99,.005,.005;.005,.990,.005;.005,.005,.990];
%pi is initial state vector
pi = [1/3,1/3,1/3];
%T is # of observations per simulation
T = 1000;
%n is # of simulations
n = 5;
%Allocate space for the state matrix
State = zeros(n,T);
Observe = zeros(n,T);
%Create dummy emission matrix, must be row stochastic 
B = ones(n,T)./T;
%loop over # of simulations
for i=1:1:n
    x = rand(1);
    if x <= (1/3)
        State(i,1) = 1;
    elseif x > (1/3) && x <= (2/3)
        State(i,1) = 2;
    else
        State(i,1) = 3;
    end
    if State(i,1) == 1
        b = -1;
    elseif State(i,1) == 2
        b = 0;
    else
        b = 1;
    end
    Observe(i,1)= normrnd(b,1);
    for k=2:1:T
        %Possible state 1,2,3
        State(k) = randsample(N, 1, true, A(State(k-1),:));
        if State == 1
            c = -1;
        elseif State == 2
            c = 0;
        else
            c = 1;
        end
        Observe(i,k)= normrnd(c,1);
    end
end




(Java) I can't figure out how to populate an array with a counter controlled loop which is required

I have to: Create an array that models a deck of cards. For example, “1_of_diamonds” represents the ace of diamonds, “2_of_diamonds” represents the 2 of diamonds, up to “13_of_diamonds”, which represents the King of diamonds. The suits clubs, hearts and spades are represented in a similar manner. All these elements should be in a single array. The array should be populated using a counter controlled loop. Output the contents of the array to the screen. Shuffle the deck.

I have the code to shuffle it working but I do not know how to populate the array with a counter controlled loop.

//this is my code

import java.util.Random;


public class Cards{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);

} //end main

public String[] shuffle(String[] deck) {
    Random rnd = new Random();
    for (int i = deck.length - 1; i >= 0; i--)
    {
        int index = rnd.nextInt(i + 1);
        // Simple swap
        String a = deck[index];
        deck[index] = deck[i];
        deck[i] = a;
    }
    return deck;

}
}// end class




Can't figure out why my while loop is getting stuck

Currently working on writing code for a Windows Forms version of the card game war. I needed a way to shuffle the list to randomize the deck. I have already defined the lists for deck and shuffledDeck as a list of strings.

When I run createDeck(), I had it output to a textbox in my windows form to ensure that it is infact creating the list properly. I also had it test to ensure that deck.Count() was equal to 52

private void shuffle()
        {
            createDeck();
            shuffledDeck = deck;
            Random r = new Random();
            int randomIndex = 0;
            while (deck.Count > 0)
            {
                randomIndex = r.Next(0, deck.Count);
                shuffledDeck.Add(deck[randomIndex]);
                deck.RemoveAt(randomIndex);
            }

This is my testing that the deck is in fact shuffled

            for (int a = 0; a <= 51; a++)
            {
                textBox1.Text += " " + shuffledDeck[a];
            }

I would expect that I would see a shuffled deck each time however whenever I run it, Visual Studio freezes and I am have to force quit the program to exit.




Getting a random number in a function in OCAML OR Telling compiler to evaluate function each time

I'm new to OCAML and was playing around with putting a marker on a random 5X5 square. I've written the example program below. "silly_method1" works but notice that it takes an argument. I don't really have argument to pass in for what I want. I'm just asking for a random number to create my robot on a particular square:

let create = {x = ( Random.int 4); y=3; face = North}

However, I get the same location each time. This makes sense to me... sort of. I'm assuming that the way I've set it up, "create" is basically a constant. It's evaluated once and that's it! I've fixed it below in silly_method2 but look how ugly it is!

let silly_method2 _ = (Random.int 10)

Every time I have to call it, I have to pass in an argument even though I'm not really using it.

What is the correct way to do this? There must be some way to have a function that takes no arguments and passes back a random number (or random tuple, etc.) And possibly related... Is there a way to tell OCaml not to evaluate the function once and save the result but rather recalculate the answer each time?

Thank you for your patience with me!

Dave

let _ = Random.self_init()

let silly_method1 x = x + (Random.int 10)
let silly_method2 _ = (Random.int 10)
let report1 x = (print_newline(); print_string("report1 begin:  "); print_int (silly_method1 x); print_string("report1 end"); print_newline(); )
let report2 y = (print_newline(); print_string("report2 begin:  "); print_int(silly_method2 y ); print_string("report2 end"); print_newline(); )

let _ = report1 3
let _ = report1 3
let _ = report1 3

let _ = report2 3
let _ = report2 3
let _ = report2 3




Parallel keyword substitution across two files

Assume two text files (file1 and file2) that are identical in structure (same n of lines), but different in content. Assume further the occasional occurrence of a keyword (e.g., "KEYW") in the same lines of both files.

$ cat file1
foo bar baz
foo KEYW baz
foo bar KEYW

$ cat file2
foo bar qux
foo qux KEYW
qux bar KEYW

I would like to replace each instance of KEYW with a random number such that the replacement is done in parallel across the two files (i.e., the first occurrence in both files is replaced with random number 1, the second occurrence in both files replace with random number 2, etc.).

$ sought_command file1 file2
# RANDOM1=123
# RANDOM2=456

$ cat file1.new
foo bar baz
foo 123 baz
foo bar 456

$ cat file2.new
foo bar qux
foo qux 123
qux bar 456

In your opinion, what is the quickest way to implement this task? Shall I try to implement it via sed, awk or Python?

--

EDIT 1:

The pseudocode I am thinking of goes like this:

1. Identify lines with KEYW and save as list.
2. Iterate through list via for-loop.
3. In each loop, do:
   3.a. Generate a random number 
   3.b. Replace the occurrence of KEYW in the current line with the random number using `sed -i -e "<line_number>s/KEYW/<random_number>/" file*`.




How can I use arrays to produce an equation in a Jlabel

I've made a java class with 3 fixed size arrays (array[15], array[30], array[50]) also I got 2 JFrame forms, the first with 3 JRadioButtons (15, 30, 50) and the second JFrame with a Jlabel which should generate an equation and a JTextField which should validate user input and also a button which should continue to the next question. If the user selects JRadioButton 15 I want the Jlabel on the second JFrame to generate 15 equations etc.

I've tried to put the code from the java class in the source code of the JFrame form, though I have to put it in a separate java class for my assignment. Also, I've searched on google and can't find anything relevant.

import java.util.Random;

public class SomGenerator {

public static int randomFill() {
    Random rdm = new Random();
    int randomNum = rdm.nextInt(50)+1;
    return randomNum;
}

public static int[] lijst1() {
    int[] array1 = new int[15];
    for(int i = 0; i < array1.length; i++) {
        array1[i] = randomFill();
    }
    return array1;
}

public static int[] lijst2() {
    int[] array2 = new int[30];
    for(int i = 0; i < array2.length; i++) {
        array2[i] = randomFill();
    }
    return array2;
}

public static int[] lijst3() {
    int[] array3 = new int[15];
    for(int i = 0; i < array3.length; i++) {
        array3[i] = randomFill();
    }
    return array3;
}

}


public class SommenFrame extends javax.swing.JFrame {

public SommenFrame() {
    initComponents();
}

public class SetSommen extends SomGenerator {
    public SetSommen() {
        //somLbl needs to generate the equation
        somLbl.setText(lijst1 + "+" + lijst1);
    }
}

I would really appreciate some help since I've looked at posts where people use the setText() property to set an array to the Label whereas I get an error, I used extends to link to the java class so I don't get why it doesn't get the array assigned to it.




Replace duplicate elements in a numpy array based on a range

I have an 1d numpy array arr as below:

arr = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])

For the duplicate elements, I wish to randomly select any one of the indices containing the same element and replace it with a value missing in between 0 and arr.shape[0].

e.g. In the given array, 7 is present in indices 1, 4 and 9. Hence, I wish to randomly select an index between 1, 4 and 9 and set its value by randomly selecting some element like 8, which is absent in the array. In the end, arr should contain 10 unique elements lying between 0 and 9 (both inclusive)

How can I do this efficiently using Numpy (possibly without needing to use any explicit loop)?




How to generate a uniformly distributed random double in C using libsodium in range [-a,a]?

The libsodium library has a function

uint32_t randombytes_uniform(const uint32_t upper_bound);

but obviously this returns an unsigned integer. Can I somehow use this to generate a uniformly distributed random double in range [-a,a] where a is also a double given by the user ? I am especially focused on the result being uniformly distributed/unbiased, so that is why I would like to use the libsodium library.




How to have a unique random number generated in a csv file every time without manual intervention?

I need to pass 10 digit alpha numeric random value (e.g. AUT******* where * denotes any random number) in a csv file.

Contents of csv file:

Code,Account1,Account2,Account3
AUT*******,ABC,DEF,GHI

This csv file will be uploaded in to a web application every time to perform some operation.

I need this value to be unique every time, before I upload the csv file to the web application so that web application considers the unique value for upload operation.

Manually we can do these steps, but I want to automate this process without any manual intervention. This is required for my Automation framework.

Please help me with some suggestion/possibilities?

Thanks, Siva




how to generate a random number with a known probability?

I would like to generate a random number between x and y with a known probability. For example, using Output=randint(0,2) i know that there is a 33% probability that Output is equal to 1.

Similarly, if Output=randint(0,3) i know that there is 25% probability that the Output is equal to 1.

How can i generate a random number similar to above to make sure that there is 40% probability that Output equal to 1?

Thanks a lot




How To Set Global Random Seed in Python

Like in R, I would like to set a random seed globally for the entire script/session, instead of having to call the random seed function every time I execute a function or run a model. I am aware that sci-kit learn uses the numpy RNG, but also could not find a way to set it globally.

I have read several posts here on this topic, such as this one: Differences between numpy.random and random.random in Python

It explains the difference between the two RNG classes, but not how to set it globally.

Is there no way of doing this except for calling the random seed EVERY time I want the output to be the same?

## Random Library

import random
##### Random seed given
random.seed(42)
print(random.random()) #will generate a random number 

##### No seed given
print(random.random()) #will generate a random number 

##### Random seed given
random.seed(42)
print(random.random()) #will generate a random number 


#############################

## Numpy Library

import numpy as np

##### Random seed given
np.random.seed(42)
print(np.random.random())

##### No seed given
print(np.random.random())

##### Same seed given
np.random.seed(42)
print(np.random.random())




How can I make an if-statement based on what has randomly been printed?

so I am creating a type of game that will involve dices. What I plan on doing is to have different things happening depending on what the player throws, it will be a 2 player game.

What I want to do is make the computer randomly generate 2 of the 6 possible dice sides. After that has been printed, the computer will move onto an if-statement where it will see ex: if a dice_1 and a dice_3 has been printed, the computer will do something. If it has printed a 1 and a 1, it will do another thing and so on.

This is what I have so far:

import random
for x in range(2):
  print random.randint(1,7) 

So basically, to repeat what I need is a way to use the if-statement to check if the random numbers are ex: 1 and 3 & another example is to check if the numbers add up to 6.

Thanks.




mercredi 24 avril 2019

Is there away to access whats inside a function with an onclick event?

**So, I want to know if its possible to access whats inside a function and use it on an onClick event.

For example:

   function random(){
       Math.floor(Math.random()*2+1)
   }

And my question is; I want to use the If statement for whats inside the function.

    if(random number ===1) do something on onClick event.




Generating a number to decide which intent to pick and move to said intent

I am currently trying to make a little minigame application in Android Studio. I have a problem - I need to generate a random number that is not the same as the previously generated number and I used said number to decide which intent I will move to. I use the code below to generate the random number which I have stored in a class where I keep things like the current score called globalVariablesGame, but when I call globalVariablesGame and ask for a random number, the lastrandomnumber for some reason doesn't change at all no matter how many are generated.

int getRandomNumber() {
randomNumber = random.nextInt(3);
while (randomNumber == lastRandomNumber){
         randomNumber = random.nextInt(3)}
lastRandomNumber = randomNumber;
return randomNumber;
}

To decide which intent I use

int nextgame = globalVariablesGame.getRandomNumber(); // Call this int to determine what the next MG  is going to be played
if (nextgame == 0) {
                    Intent myIntent = new Intent(context, Minigameone.class);
                    myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    finish();
                    startActivity(myIntent);
                }
                if (nextgame == 1) {
                    Intent myIntent = new Intent(context, Minigametwo.class);
                    myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    finish();
                    startActivity(myIntent);
                }

Obviously I need the lastrandomnumber to actually change when I generate a new number but it doesn't, any help?




How can I fit a randomly generated number to a custom "bell curve" distribution?

I designed the values to fit to an off-center bell-curve. Trial runs seem to give desirable results, but is there anything I am missing?

What I have discovered

I found a question that thought would help, but they are using standard deviation.

JavaScript Math.random Normal distribution (Gaussian bell curve)?

From the question above:

  • Q: Is Math.random already normally-distributed?
  • A: No

What I have

const ranks = [
  ['X'   , 0.01, 0.01],
  ['SSS' , 0.03, 0.04],
  ['SS'  , 0.06, 0.10],
  ['S'   , 0.08, 0.18],
  ['A'   , 0.11, 0.29],
  ['B'   , 0.14, 0.43],
  ['C'   , 0.21, 0.64],
  ['D'   , 0.17, 0.81],
  ['E'   , 0.12, 0.93],
  ['F'   , 0.07, 1.00]
];

log('Total:', ranks.reduce((a, b) => a + b[1], 0).toFixed(2));
for (let i = 0; i < 10; i++) {
  generate();
}

/* Public */
function generate() {
  let percent = Math.random();
  log(percent.toFixed(4), getRank(percent));
}

/* Protected */
function getRank(percent) {
  return ranks.filter((rank, index) => {
    let min = index > 0 ? ranks[index - 1][2] : -1;
    return percent > min && percent <= rank[2];
  })[0][0];
}

/* Private */
function log() {
  let el = document.createElement('DIV');
  el.innerHTML = [].slice.call(arguments).join(' ');
  el.className = 'log-line';
  document.body.appendChild(el);
}
body {
  background: #666;
}

.log-line {
  font-family: monospace;
  background: #AAA;
  margin: 0.5em 0.25em;
  padding: 0.25em;
}

.log-line::before {
  content: '>>> ';
}



How do I use an array to calculate percentages using randomly generated values?

I need my program to display the expected and actual percentages of how often the sums of two dice appear. I can't get the expected percentages to display the array, it always comes out as 0. I am not sure how to calculate the actual percentages using the random values. The sum and tally part work fine. I also keep getting a "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11 at Dice.main(Dice.java:30)" error at the end.

public class Dice {

    public static void main(String[] args) {

        int [] counters=new int[13]; //array of counters
        int [] expected={1/36,2/36,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36};
        int [] actual=new int[13];

        //initialize array values to 0
        for(int i=1; i<counters.length; i++) {
            counters[i]=0;
        }

        for(int i=1; i<actual.length; i++) {
            actual[i]=0;
        }

        //generating die values and updating counter
        for(int i=1; i<=36000; i++) {
            int d1=(int) (Math.random()*6)+1;
            int d2=(int) (Math.random()*6)+1;
            int sum= d1+d2;
            counters[sum]++;
        }

        //display table
        System.out.printf("%10s %10s %15s %15s \n", "Sum:", "Tally:", "Expected Percentage (%):", "Actual Percentage (%):");
        for(int i=2; i<counters.length; i++) {
            System.out.printf("%8d %10d %10d %20d\n", i, counters[i], expected[i], actual[i]);
        }
    }

}


I expect the output to show as decimals or as fractions, but I only get zeros.




How do you create a for loop in MATLAB that evaluates a random variable then stores answer in matrix?

My code is not working properly! I am attempting to call on a random exponential random variable with lambda = 10. The amount of times I call it is equal to (a), I can choose whatever I want. If the random variable is within the acceptable interval of 0 and 1, I want to evaluate it in the equation given and store it in h (a zero matrix I created before the for loop). If the random variable is not in the acceptable range, the equation just equals 0. I want to store all values in the h matrix (evaluated and zeros). I think my logic is correct, but after I run it, my h matrix is still all zeros.

function Importance1(a)

%samplesize = a;
%Hx = gx/fx
% equation to use
%hx = @(x) ((abs(cos(pi*x)).^(2.5)).*exp(-10*x))./(exp(-2*abs(x))); 

x = exprnd(10, a, 1); %exponential X ~ (10)
h = zeros(a, 1);
for i=1:1:a
    if x(i) <= 1 && x(i) >= 0
        h(i)=((abs(cos(pi*x(i))).^(2.5)).*exp(-10*x(i)))./(exp(-2*abs(x(i))));
    else 
        h(i) = 0;
    end
end 

mcvalue1 = (1/a)*sum(h); %expected value

%Actual value of hx
hx = @(x) ((abs(cos(pi*x)).^(2.5)).*exp(-10*x))./(exp(-2*abs(x)));
hi = integral(hx, 0,1);

%calculate the relative error; from the known value
error1 =((abs(mcvalue1-hi))/(hi)).*100;




Why my created random function just work for one time?

Thank you for helping me!

There is a piece of random function I found on the Internet, called GetRandom. I put it like below

 public static double GetRandom(double[] array)
  {    
       Random ran = new Random();
    int n = ran.Next(array.Length);
    return array[n];
  }

 private void Window_Activated(object sender, System.EventArgs e)
    {   


        c1 = c-GetRandom(arr);
        c2 = c-GetRandom(arr);
......

    }

arr is a double arry containing a a few doubles. c1,c2,c3 .... are all double. Howeve, it seems that every GetRandom(arr) in the last few lines return the same result.How come? The n in GetRandom can't be refreshed after each use?




Why is not the new game equal to the previous one if I have reinitialized the seed and they have the same seed?

I am training a neural network to play a game. The game is randomly generated, but I want the agent to train and play always in the same environment. Therefore I always initialize the seed before starting a new game. However, the only result I see is that when I run the program, the games are all different, but when I run it for a second time, the games are equal to the first time. It seems like I correctly set the seed, but I am not able to reinitialize it.

I could not upload the code properly to stackoverflow, so here is the link: https://gist.github.com/AOrtizDZ/725c1efc191d3aeb854dddbc1cbacbd3

Here is the part of the code that initiates the game each time:

def game(genome, config):

random.seed(12)

global reward, mustcreate, dontcreate, must_creation_counter, score
global forbidden_creation_counter

net = neat.nn.FeedForwardNetwork.create(genome, config)

pygame.init()
pygame.mixer.init()
# screen = pygame.display.set_mode((WIDTH, HEIGHT))
# pygame.display.set_caption("Dinosaur")
clock = pygame.time.Clock()
# font = pygame.font.Font(None, 35)

players = list()
for i in range(num_players):
    players.append(Player(keys[i], colors[i], semicolors[i], i * 45))

enemies = list()

# Game loop
running = True
fps_counter = 0
reward = 0
action = np.zeros([3])
action[0] = 1

while running:

    reward += 1
    # keep loop running at the right speed

    #   clock.tick(FPS)

    # Process input (events)

    for event in pygame.event.get():
        # check for closing window

        if event.type == pygame.QUIT:
            running = False

    if (random.random() < prob_per_second / FPS and not dontcreate) or mustcreate:

        enemies.append(Enemy(level))

        dontcreate = True

        mustcreate = False

        must_creation_counter = 0

    else:
        must_creation_counter += 1

    if dontcreate == True:

        forbidden_creation_counter += 1

        if forbidden_creation_counter == 30:
            dontcreate = False

            forbidden_creation_counter = 0

    if must_creation_counter == 120:
        mustcreate = True

    #   screen.fill(WHITE)
    # Update

    for player in players:
        player.update(action)

    #       screen.blit(player.image, player.rect)
    # Draw / render

    for enemy in enemies:

        enemy.update()

        #       screen.blit(enemy.image, enemy.rect)

        if enemy.rect.right < 0:
            enemies.remove(enemy)

            score += 1

        for player in players:

            if pygame.sprite.collide_rect(player, enemy):
                player.choque()

    for player in players:

        if player.inmortal == True:

            player.counter += 1

            if player.counter == 120:
                player.counter = 0

                player.inmortal = False

        if player.vidas == 0:
            running = False

            return reward

    #       screen.blit(font.render(str(player.vidas), True, player.color), [60 + 60 * players.index(player), 40])

    # enemies.sort(key=operator.attrgetter('rect.left'))
    enemies_coord = list()

    for enemy in enemies:
        enemies_coord.append(enemy.rect.left)

        enemies_coord.append(enemy.rect.width)

        enemies_coord.append(enemy.rect.height)

        enemies_coord.append(enemy.speedx)

    player_coord = [player.rect.left,
                    player.rect.top,
                    player.speedy if player.speedy != 0.5 else 0]

    state = player_coord + enemies_coord

    while len(state) < 15:
        state.append(0)

    while len(state) > 15:
        state.pop()

    output = net.activate(state)
    max_Q = np.argmax(output)
    action = np.zeros([3])

    action[max_Q] = 1

    if max_Q == 1: reward -= 2

    #   screen.blit(font.render(str(reward), True, BLACK), [WIDTH - 60, 40])

    #   pygame.draw.line(screen, BLACK, (0, HEIGHT - 10), (WIDTH, HEIGHT - 10), 3)
    # *after* drawing everything, flip the display

    #   pygame.display.flip()

    fps_counter += 1




How to pick a random value out of an array with a specific proportion?

I'm using Javascript and I would like to pick a random value out of an array. The problem is that actually I want to do the selection with specific proportions.

What does it mean?

I have the following values - 'INFO', 'CRITICAL', 'DEBUG', 'ERROR'

And I want to pick the values with the following ratio:

1. INFO - 30% 2. CRITICAL - 5% 3. DEBUG - 55% 4. ERROR - 10%

This is how I currently randomally pick a value -

var diffSev = ['INFO', 'CRITICAL', 'DEBUG', 'ERROR']
output['testSev'] = diffSev[Math.floor(Math.random() * diffSev.length)];

I would like to add a logic that will pick the values with the ratio that I need. Thanks!!




Duplicate, submitted URL not selected as canonical instead random url of mobile website is taken

User-declared canonical: https://www.paperboy.com/vijayavani-newspaper-read Google-selected canonical: https://m.paperboy.com/sakshi-newspaper-read

i want the google selected url to be same as user declared url.




How to pick random items through cumulative probability?

Exercise Background

The exercise consists in generating a 2D map with a user given x,y size of said map, and then place on each cell of the map random items from a table. I have a cell in an [x, y] coordinate of an Items matrix and I have to pick items randomly for every cell of this matrix.

My Problem

I have to select random items from a table of 4 items that have their probabilities shown in cumulative probability, and a cell that has such items can have more than 1 and different combinations of those items.

I don't really know how to go about this problem, taking in account that 2 of the items have the same probability on the given table for the homework.

This is the table of probability given:

Food - 1
Weapons - 0.5
Enemy - 0.5
Trap - 0.3

My Items enumeration:

[Flags]
enum Items
{
    Food = 1<<0,
    Weapon = 1<<1,
    Enemy = 1<<2,
    Trap = 1<<3
}

Again, the expected output is to pick randomly through this percentages what items does 1 cell have. What I'd like to have as an answer would be just a start or a way to go about this problem please, I still want to try and do it myself, avoid complete code solutions if you can.




List of films to randomly display in a sortable list

I have a sortable list, within this function I also have some code to display the list in a random order, however this seems to have stopped working, can anyone see why the random list is not working, ive been looking for hours now and cant work it out.

HTML

<div class="col-md-5">
            <ul id="new_fields" class="updownrow">
                <li id="field_id_1"  class="ui-state-default border-roundFirst border border-secondary">The Abyss <span class="updownbtn movetop fa fa-angle-double-up"></span><span class="float-right"><a href="">down</a> <a href="">up</a></span> </li>
                <li id="field_id_2"  class="ui-state-default border-round border border-secondary">Aliens <span class="updownbtn movetop fa fa-angle-double-up"></span><span class="float-right up"> <a href="">down</a> <a href="">up</a></span></li>
                <li id="field_id_3"  class="ui-state-default border-round border border-secondary">The Terminator <span class="updownbtn movetop fa fa-angle-double-up"></span><span class="float-right"><a href="">down</a> <a href="">up</a></span></li>
                <li id="field_id_4"  class="ui-state-default border-round border border-secondary">Terminator 2: Judgement Day <span class="updownbtn movetop fa fa-angle-double-up"></span><span class="float-right"><a href="">down</a> <a href="">up</a></span></li>
                <li id="field_id_5"  class="ui-state-default border-round border border-secondary">Avatar <span class="updownbtn movetop fa fa-angle-double-up"></span><span class="float-right"><a href="">down</a> <a href="">up</a></span></li>
                <li id="field_id_6"  class="ui-state-default border-round border border-secondary">Titanic <span class="updownbtn movetop fa fa-angle-double-up"></span><span class="float-right"><a href="">down</a> <a href="">up</a></span></li>
                <li id="field_id_7"  class="ui-state-default border-round border border-secondary">Piranha II: The Spawning <span class="updownbtn movetop fa fa-angle-double-up"></span><span class="float-right"><a href="">down</a> <a href="">up</a></span></li>
            </ul>
        </div>

JS

function sortable () {
        jQuery("#new_fields").sortable({
            cursor: 'move',
            // post
            update: function () {
                var order = jQuery('#new_fields').sortable('serialize');
                jQuery.ajax({
                    type: "POST",
                    url: "<?php filmlist( 'url' ); ?>/wp-admin/admin-ajax.php",
                    data: "action=update_field_order&" + order
                });
            }
        });
        jQuery("#new_fields").disableSelection();

        var ul = document.querySelector('ul');
        for (var i = ul.children.length; i >= 0; i--) {
            ul.appendChild(ul.children[Math.random() * i]);
        }

        lists = document.getElementsByClassName('ui-state-default');
        x = [];
        for (var i = 0, im = lists.length; im > i; i++) {
            x[i] = lists[i].id;
            console.log(x);
        }
    },




mardi 23 avril 2019

How to compile a numba jit'ed function with variable input type?

Say I have a function that can accept both an int or a None type as an input argument

import numba as nb
import numpy as np

jitkw = {"nopython": True, "nogil": True, "error_model": "numpy", "fastmath": True}


@nb.jit("f8(i8)", **jitkw)
def get_random(seed=None):
    np.random.seed(None)
    out = np.random.normal()
    return out

I want the function to simply return a normally distributed random number. If I want reproducible results, seed should be an int.

get_random(42)
>>> 0.4967141530112327
get_random(42)
>>> 0.4967141530112327
get_random(42)
>>> 0.4967141530112327

If I want random numbers, seed should be left as None. However, if I do not pass an argument (so seed defaults to None) or explicitly pass seed=None, then numba raises a TypeError

get_random()
>>> TypeError: No matching definition for argument type(s) omitted(default=None)
get_random(None)
>>> TypeError: No matching definition for argument type(s) omitted(default=None)

How can I write the function, still declaring the signature and using nopython mode for such a scenario?

My numba version is 0.43.1




How to set a string based on a random number in a foreach loop

I want to add a variable to a list but set it too a random string out of a set of three strings, i want to do this in a foreach loop. I am new to programming.

This is just an example:

        foreach (List li in list)
        {
            if (li.name == "name")
            {
                rand = RandomNumber(1, 4); // Random is called in 
                                              different method

                if (rand == 1)
                {
                    newName = "bob";
                }
                else if (rand == 2)
                {
                    newName = "ben";
                }
                else if (rand == 3)
                {
                    newName = "dave";
                }

                class2 obj = new class2(newName, middleName, surname);
                List2.Add(obj);
            }
        }

Every time i print out each object in the list it will set newName to the same string, I want newName to be different




Sport league Scheduling: Uneven distributed matchups

I'm currently trying to create schedules for different leagues. I have read questions on round robin and am also able to create a schedule for a season with a first an a second half. However, what I'm trying to achieve is:

  • Leagues with 16 or 32 teams
  • 64 games per season (in 16 teams leagues play every opponent 4x, in 32 team leagues play every opponent twice)
  • Four to seven Games per day
  • No multiple games per team per day
  • Even distribution of home and away games
  • Games on consecutive days are possible, but not more than two in a row

What have I tried so far? As a first step, I created a list of all possible matchups with itertools:

import itertools

p = ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10', 'A11', 'A12', 'A13', 'A14', 'A15', 'A16', 'A17', 'A18', 'A19', 'A20', 'A21', 'A22', 'A23', 'A24', 'A25', 'A26', 'A27', 'A28', 'A29', 'A30', 'A31']

f = list(itertools.combinations(p, 2))

# [('A0', 'A1'), ('A0', 'A2'), ('A0', 'A3'), ... ]

From here on, I might chose a wrong path, deciding to work with indexes. Hence, I created a list of lists c, where every sub-list is a copy of f. The list f is represented n times in c depending on the size of the league (16 teams: 4x; 32 teams: 2x).

import itertools
import random

def get_correct_ind(list_of_lists):
    if len(list_of_lists[0]) == 0:
        return 1
    else:
        return 0

def get_a_matchup(list_of_lists):
    corr_ind = get_correct_ind(list_of_lists)
    list_length = len(list_of_lists[corr_ind])-1

    if list_length == 0:
        choice_ind = 0
    else:
        choice_ind = random.randint(0,list_length)

    choice = list_of_lists[corr_ind][choice_ind]
    meta = {'corr_ind':corr_ind, 'choice_ind':choice_ind}
    return choice,meta

# 16 teams:
f = list(itertools.combinations(p, 2))
g = list(itertools.combinations(p, 2))

c = [f, g]

day = 0
schedule = {}
cond1 = True
while cond1:
    if len(c[0]) == 0 and len(c[1]) == 0: cond1 = False
    day += 1

    matchups_today = []
    how_many_games_today = random.randint(4,7)

    counter = 0
    cond2 = True
    while cond2:
        counter += 1
        if counter == how_many_games_today: cond2 = False

        matchup,meta = get_a_matchup(c)

        invalid = False
        for team in matchup:
            if invalid: break
            for existing_matchup in matchups_today:
                if invalid: break
                if team in existing_matchup:
                    invalid = True
                    break

        if not invalid:
            matchups_today.append(matchup)
            c[meta['corr_ind']].pop(meta['choice_ind'])

    schedule[day] = matchups_today

As you can see, this approach is getting messy very quickly and doesn't even consider even distribution of home/away games, the rule of no more than two games in a row for each team and is also producing an error in this line: choice_ind = random.randint(0,list_length) (ValueError: empty range for randrange() (0,0, 0)) which I don't get as I control if list_length equals zero. Any help/hint on how to proceed best would be appreciated.




lundi 22 avril 2019

How to fill array with random numbers limited to 0-20

I am having trouble placing the random generator in the array, how can I get #20 random numbers from 0-9 in the array? Then you count the occurrences of those numbers.

import java.util.Random;

public class CountDigits {

public static void main(String[] args) {



    Random digit = new Random(); 

    int Random[] = new int [20];

    int Digits[] = {0,1,2,3,4,5,6,7,8,9}; 

    int Count [] = new int [10]; 


    for ( int i = 0; i < Digits.length; i++) {


        for( int j = 0; j < Random.length; j++) {

            if ( Digits [i] == Random [j] ) 
                Count[i]++; 
        }

    }


    for ( int i = 0; i < Count.length; i++) {

        if ( Count[i] == 1) 
            System.out.printf(" %d  occurs  1 time " , Digits[i] ); 

        else
            System.out.printf("%d occurs %d times" , Digits[i], Count[i]); 

    }

result so far:: 0 occurs 20 times1 occurs 0 times2 occurs 0 times3 occurs 0 times4 occurs 0 times5 occurs 0 times6 occurs 0 times7 occurs 0 times8 occurs 0 times9 occurs 0 times




How do i create a method which grabs a random value from a String array? [duplicate]

This question already has an answer here:

I am writing a small OOP for the card game Mafia. Right now, I'm trying to create a Method that will: grab a random value(a role) from the array, role, and return it. Thanks so much in advance.

Here is the array

public static String[] role = {"Mafia", "Angel", "Cop", "Civilian"};

Below is what I currently have for my Method of grabbing a random value, as you can see, I'm clueless on what to write up next lol.

public static String[] role() {
    Random randomRole = new Random();
}




Does anyone know of any p.r.n.g based on laws that govern fractal geometry?

First, I am not a programmer, so sorry in advance for my ignorance. My question is, are there any prngs or rngs that base their outcome not from random event such as keystrokes or atmospheric conditions but from a set of algorithms based on the laws that produce fractal geometry or an exponential curve.

Thank you....this may get voted down or out, but please be patient.

Jon H.




random.randint() call with -1?

Can someone explain why the range in the random.randint(0, len(messages) - 1) has a minus 1 at the end? The list has 9 values:

import random

messages = ['It is certain',
            'It is decidedly so',
            'Yes definitely',
            'Reply hazy try again',
            'Ask again later',
            'Concentrate and ask again',
            'My reply is no',
            'Outlook not so good',
            'Very doubtful']

select_number = random.randint(0, len(messages) - 1)
list_select  = messages[select_number]
print(list_select)




C++ program not decrementing correcelty

so I am making a program where you can add marbles to a bag. You chose what color you want, then the number of marbles you want to add, and then if that color marble is either cool, boring, or weird. so if you want to add 10 blue marbles, and then you chose cool. You will have ten total marbles and ten marbles that are blue and cool. I go to remove a random marble from the marbles that are stored already after I add. For some reason, it isn't working at all. I attempt to get a random number and assign that random number to a description of a current marble that has already been added. Say if the random number generated is 1 it will remove a " red cool marble " I obviously can't remove a marble that hasn't been added so I added a DO while loop, which basically loops back through the random number generator until it finds a number that satisfies the criteria. Here is my code, any thoughts? :

I tried changing the position of my Do while loop.

void remove() {



srand(time(0));

do {
randomnum = (rand () % max) + 1;





if (randomnum == 1 && redcool > 0)  {

  red--;
  redcool--;
  cout << "The random marble removed was a red and cool marble" <<endl;
}
else if (randomnum == 2 && redweird > 0) {
cout << "The random marble removed was a red and weirdl marble" <<endl;
  red--;
  redweird--;
}
else if (randomnum == 3 && redboring > 0) {
cout << "The random marble removed was a red and boring marble" <<endl;
  red--;
  redboring--;
}
else if (randomnum == 4 && greencool > 0) {
cout << "The random marble removed was a green and cool marble" <<endl;
  green--;
  greencool--;
}
else if (randomnum == 5 && greenweird > 0) {
cout << "The random marble removed was a green and weird marble" <<endl;
  green--;
  greenweird--;

}
else if (randomnum == 6 && greenboring > 0) {
cout << "The random marble removed was a green and boring marble" <<endl;
  greenboring--;
  green--;
}
else if (randomnum == 7 && greenboring < 0) {
  cout << "The random marble removed was a green and cool marble" <<endl;
    greencool--;
    green--;

}
else if (randomnum == 8 && bluecool >0) {
cout << "The random marble removed was a blue and cool marble" <<endl;
  blue--;
  bluecool--;

}
else if (randomnum == 9 && blueweird > 0) {
cout << "The random marble removed was a blue and weird marble" <<endl;
  blue--;
  blueweird--;
}
else if (randomnum == 10 && blueboring > 0) {
cout << "The random marble removed was a blue and boring marble" <<endl;
  blue--;
  blueboring--;
}

}while (randomnum == 1 && redcool > 0 || randomnum == 2 && redweird >0 || randomnum == 3
&& redboring > 0 || randomnum == 4 && greencool > 0 || randomnum == 5 && greenweird >0 || randomnum == 6
&& greenboring > 0 || randomnum == 7 && bluecool > 0 || randomnum == 8 && blueweird >0 || randomnum == 9
&& blueboring > 0);


bag--;

the expected result would say I add ten marbles that are blue and cool. When I go to remove a random marble it will then decrement a blue and cool marble because that is the only values that are in the bag. currently, nothing is even being removed.




Python error: it gives me a number even if it should close [duplicate]

This question already has an answer here:

I'm a beginner in Python and I'm getting some trouble in a code, which should be something like a "dice simulator". when the program askes you if you want a dice roll, you can choose Y or N. When I chose N it gets me a number, even if it should exit the program

i've tried this:

while 1 == 1:
start = input("Do you want a dice roll? (Y/N) \n")
if start == "Y" or "y":
    number = random.randint(1,6)
    print(number)
else:
    sys.exit(0)

and this

while 1 == 1:
    start = input("Do you want a dice roll? (Y/N) \n")
if start != "n" or "N":
    number = random.randint(1,6)
    print(number)
else:
    sys.exit(0)




Robot Framework : Random Selection of Drop downs

I need some help, I want to create a test that will randomly get the value during test case since in my case I declared it in my code, how can I make this randomly?

Heres my code

html

<select name="gender">
    <option>Please Select</option>
    <option value='Male'>Male</option>
    <option value='Female'>Female</option>
</select> 

robot

*** Test Cases ***
Select From List By Value    xpath://select[@name='gender']    Male




dimanche 21 avril 2019

c++ can't figure out why for loop isn't showing different parts of array

So I'm finishing up a c++ program, where I needed 2 virtual dice to roll, and then display what each dice rolled and which one was higher. I'm so close to finishing and I know I'm missing something stupid, but when I display the rolls, they are all the same. Not sure if the problem is in the for loop or the section that actually generates the numbers.

                    for (int i = 0; i < rounds; i++)
                    {

                            //fills array with randomly rolled numbers
                            score[i][0] = player1->roll();
                            score[i][1] = player2->roll();

                            cout << "Player 1 dice is " << player1->getType();
                            cout << " with " << player1->getSides() << " sides." << endl;

                            cout << "Player 2 dice is " << player2->getType();
                            cout << " with " << player2->getSides() << " sides." << endl;


                            cout << "Player 1 rolls " << score[i][0] << endl;
                            cout << "Player 2 rolls " << score[i][1] << endl;
                            //tests to see who won each round and adds
                            if (score[i][0] > score[i][1])
                                    p1Score++;
                            else if (score[i][0] < score[i][1])
                                    p2Score++;

                            cout << "Player 1 has won " << p1Score << " times" << endl;
                            cout << "Player 2 has won " << p2Score << " times" << endl;
                            cout << "-----------------------------------------" << endl;
                    }

                    //tests to see who won the game overall
                    if (p1Score > p2Score)
                            cout << "Player 1 wins." << endl;
                    else if (p1Score < p2Score)
                            cout << "Player 2 wins." << endl;
                    else
                            cout << "The players have tied." << endl;
                    delete[] score;

            }

};

endif

OUTPUT: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Welcome. What would you like to do? 1. Play game 2. Exit game 1 How many rounds will be played? 4 What type of die for player 1? Please enter 1 for regular and 2 for loaded. 2 What type of die for player 2? Please enter 1 for regular and 2 for loaded. 1 What size die for player 1? 6 What size die for player 2? 7 Player 1 dice is loaded with 6 sides. Player 2 dice is regular with 7 sides. Player 1 rolls 0 Player 2 rolls 3 Player 1 has won 0 times

Player 2 has won 1 times

Player 1 dice is loaded with 6 sides. Player 2 dice is regular with 7 sides. Player 1 rolls 0 Player 2 rolls 3 Player 1 has won 0 times

Player 2 has won 2 times

Player 1 dice is loaded with 6 sides. Player 2 dice is regular with 7 sides. Player 1 rolls 0 Player 2 rolls 3 Player 1 has won 0 times

Player 2 has won 3 times

Player 1 dice is loaded with 6 sides. Player 2 dice is regular with 7 sides. Player 1 rolls 0 Player 2 rolls 3 Player 1 has won 0 times

Player 2 has won 4 times

Player 2 wins.

and here is my roll function:

            //function to generate a random number
            virtual int roll()
            {
                    srand((unsigned)time(NULL));
                    return (rand()%sides) + 1;
            }

sorry if this is formatted terribly, first post here. any help appreciated, thanks




Monte Carlo simulations in Python using quasi random standard normal numbers using sobol sequences gives erroneous values

I am trying to perform Monte Carlo Simulations using quasi random standard normal numbers. I understand that we can use sobol sequences to generate uniform numbers, and then use probability integral transform to convert them to standard normal numbers. My code gives unrealistic values of the simulated asset path:

import sobol_seq
import numpy as np
from scipy.stats import norm

def i4_sobol_generate_std_normal(dim_num, n, skip=1):
    """
    Generates multivariate standard normal quasi-random variables.
    Parameters:
      Input, integer dim_num, the spatial dimension.
      Input, integer n, the number of points to generate.
      Input, integer SKIP, the number of initial points to skip.
      Output, real np array of shape (n, dim_num).
    """

    sobols = sobol_seq.i4_sobol_generate(dim_num, n, skip)

    normals = norm.ppf(sobols)

    return normals

def GBM(Ttm, TradingDaysInAYear, NoOfPaths, UnderlyingPrice, RiskFreeRate, Volatility):
    dt = float(Ttm) / TradingDaysInAYear
    paths = np.zeros((TradingDaysInAYear + 1, NoOfPaths), np.float64)
    paths[0] = UnderlyingPrice
    for t in range(1, TradingDaysInAYear + 1):
        rand = i4_sobol_generate_std_normal(1, NoOfPaths)
        lRand = []
        for i in range(len(rand)):
            a = rand[i][0]
            lRand.append(a)
        rand = np.array(lRand)

        paths[t] = paths[t - 1] * np.exp((RiskFreeRate - 0.5 * Volatility ** 2) * dt + Volatility * np.sqrt(dt) * rand)
    return paths

GBM(1, 252, 8, 100., 0.05, 0.5)

array([[1.00000000e+02, 1.00000000e+02, 1.00000000e+02, ...,
        1.00000000e+02, 1.00000000e+02, 1.00000000e+02],
       [9.99702425e+01, 1.02116774e+02, 9.78688323e+01, ...,
        1.00978615e+02, 9.64128959e+01, 9.72154915e+01],
       [9.99404939e+01, 1.04278354e+02, 9.57830834e+01, ...,
        1.01966807e+02, 9.29544649e+01, 9.45085180e+01],
       ...,
       [9.28295879e+01, 1.88049044e+04, 4.58249200e-01, ...,
        1.14117599e+03, 1.08089096e-02, 8.58754653e-02],
       [9.28019642e+01, 1.92029616e+04, 4.48483141e-01, ...,
        1.15234371e+03, 1.04211828e-02, 8.34842557e-02],
       [9.27743486e+01, 1.96094448e+04, 4.38925214e-01, ...,
        1.16362072e+03, 1.00473641e-02, 8.11596295e-02]])


Values like 8.11596295e-02 should not be generated, hence I think there is something wrong in the code. If I use standard normal draws from the numpy library rand = np.random.standard_normal(NoOfPaths) then the price matches with the Black Scholes price. Hence I think the problem is with the random number generator. The value 8.11596295e-02 refers to a price in a path, and its very unlikely that the price would come down from 100 (initial price) to 8.11596295e-02

References: https://stats.stackexchange.com/questions/27450/best-method-for-transforming-low-discrepancy-sequence-into-normal-distribution, Recommendations for Low Discrepancy (e.g. Sobol) quasi-random sequences in Python/SciPy?, https://github.com/naught101/sobol_seq

Any help is appreciated.




Does downsampling a random sequence make it less random? Is there a principle/theorem that shows this?

I'm wondering whether downsampling a random (or psuedorandom) sequence makes it less random or preserves its randomness. For example, if you take a series of psuedorandom bytes, as shown in the code below, and throw out all but the alphanumeric characters, is the resulting string of alphanumeric characters still psuedorandom? What about for a random case?

Is there a mathematical or computing principle or theorem that shows this one way or the other?

I looked at this question: Is a subset of a random sequence also random?

But this does not cover specifically a selection process that includes knowledge of the values that are being selected. The answer by MusiGenesis seems to say that this might cause less randomness.

// Open the /dev/urandom file to read random bytes
ifstream rand_file("/dev/urandom");

if (!rand_file) {
    cout << "Cannot open /dev/urandom!" << endl;
    return return_code::err_cannot_open_file;
}

string password("");
vector<char> rand_vec(rand_vec_length, 0);
while (password.length() < pwd_length) {
     fill_rand_vec(rand_vec, rand_file);

    // Iterate through the vector of psuedo-random bytes and add 
    // printable chars to the password
    for (auto rand_char : rand_vec) {
        if (isprint(rand_char) && !isspace(rand_char)) {
            password += rand_char;
        }

        if (password.length() >= pwd_length) {
            break;
        }
    }
}




Whenever i choose a random file from a folder it says file not found

I'm trying to make the code to choose a random file from a folder and tweet it on tweeter, but i get an error

I'm on windows 10, haven't tried anything else.


path ='C:/Users/Name/Desktop/twitbot/home/gay'
files = os.listdir(path)
index = random.randrange(0, len(files))

message = "Picture of the moment!"
with open(files[index], 'rb') as photo:
    twitter.update_status_with_media(status=message, media=photo)

I expect the code to choose a picture and to post it on Twitter, but it says 'FileNotFoundError: [Errno 2] No such file or directory: '753.jpg''




How can I generate a reference number in a certain pattern in php

I would like to generate a sequential number.

basically I have a form and on that form is a textbox for a reference number - I would like that number generated. Ideally I would like it to be in the format of 'MB.P1.A, all sequential, nothing random.

I am not sure how to go about this. whether it needs to be a database thing or text file thing.

MB is constant but the number after P will change randomly as well as the last letter.

How can I do this in php?




How do I generate random numbers in a range?

I'm creating a program for school that works as follows: user thinks of a number and computer tries to guess it. computer generates a random number, asks user if number is higher or lower, then if the number is higher it takes that number and sets that as the minimum value for the random number range(ex. generates a 47, then will only generate numbers between 47-100). if the number is lower it takes the random number that was generated and makes that the minimum value.

My problem is with the random number generator and the range. I can generate the random number by seeding it at the start { srand(time(NULL));} then generate a number { rand_num = rand()%100; } generates a number between 1-100. but I can't figure out how to generate a number in a range (example 47-89). thought it was {rand_num = rand()%89 + 47}, but this doesn't seem to work.

Github: https://gist.github.com/EthanA2020/e121b27ab80fa6e2d32df1396e62b632

{

srand(time(NULL));
do {
rand_num=rand()%47+89;
cout << rand_num << endl;
cout << "enter: "; cin >> userquitval;
}while (userquitval!=7);

}




Why my function returns so big random values when it has a range?

I'm trying to get random float values in a range in a pointer but it gives me some very big numbers. I think my error is in the function calling but i'm not sure.

This is the function:

#include <time.h>
#include <stdlib.h>
void random_values(float *arr, int N) // "arr" is used like an array to 
                                      //keep random float values

{                                     // "N" is the length of the array
    int i;
    float max_range=1000.00;
    arr=(float *)(malloc(sizeof(float)*N));
    srand(time(0));
    for(i=0; i<N; i++)
    {
        *(arr+i)=((float)rand()/(float)(RAND_MAX)) * max_range;

    }
    free(arr);
}

Here I call the function and try to print it out:

random_values(arr, length);
for(i=0;i<length;i++)
    printf("%.2f\n", *(arr+i));




How to know when given secure PRNG, modified PRNG is secure or insecure?

I'm having trouble to distinguish modified pseudo-random generators when given G: {0, 1}^s --> {0, 1}^n is a secure PRNG. I want to know whether some G's are secure PRNG or not. And I also want to know the reason why it can be distinguished from a real random generator.

These are G'(k)s...

G'(k) = G(k)||G(k+1)

G'(k) = G(k)||G(2*k)

G'(k) = G(k)||k

Thank you for your answering!




C : Does not print the array index in variadic functions

I want to print the index in the array with random. But I cant.

Main.c:

RastgeleKarakter randomB = overload5_specifiedRandom(6,'g','y','u','c','n','e');

RastgeleKarakter.c

RastgeleKarakter overload5_specifiedRandom(int args,...){
  va_list list;
  va_start(list, args);
  char array[7];
  char* test;
  int sayi = (int) ((Now())%args);
  for(int i = 1; i <= args; i++){
    array[args] = (char) va_arg(list,int);
    printf("%c ", array[args]);
  } 
  printf("%d",sayi);
  va_end(list);
}

Out:

g y u c n e 3╝

I want this out :

'u' or 'g' or 'c' 




How to instantiate prefabs randomly one next to each other between vector double range

I am trying to instantiate 6 prefabs from an array at random positions within a range. I can instantiate the prefabs randomly as needed the problem lies in their positioning I need them one next to each other but the vector positions between them are very small

X. -0.37 to 0.233 Z. 0.268 to -0.041

var obj = Instantiate(CharToPrefab[randomChar]);

        obj.transform.position = new Vector3(
            Random.Range(-0.37, 0.233),
            -0.1741,
            Random.Range(0.268, -0.041)
            );

I expect the prefabs to instantiate anywhere between those points, the errors I recieve are that I cannot convert double to float but I need the prefabs between those two small points as the game relies on leap motion technology in which the play in unable to reach outside those boundaries that I have created for my game play view.

Is there an alternative way to have these cube prefabs positioned where needed?




samedi 20 avril 2019

Python Code to generate quasi random standard normal numbers using sobol sequences gives erroneous values

I have a Python code to generate quasi random standard normal numbers using sobol sequences, however some values generated are greater than 1. Hence I must be doing something wrong. Code:

import sobol_seq

def i4_sobol_generate_std_normal(dim_num, n, skip=1):
    """
    Generates multivariate standard normal quasi-random variables.
    Parameters:
      Input, integer dim_num, the spatial dimension.
      Input, integer n, the number of points to generate.
      Input, integer SKIP, the number of initial points to skip.
      Output, real np array of shape (n, dim_num).
    """

    sobols = sobol_seq.i4_sobol_generate(dim_num, n, skip)

    normals = norm.ppf(sobols)

    return normals

NoOfPaths = 8

rand = i4_sobol_generate_std_normal(1, NoOfPaths)
lRand = []
for i in range(len(rand)):
    a = rand[i][0]
    lRand.append(a)
rand = np.array(lRand)

Output : 
Out[34]:
array([ 0.        ,  0.67448975, -0.67448975, -0.31863936,  1.15034938,
        0.31863936, -1.15034938, -0.88714656])


References : Recommendations for Low Discrepancy (e.g. Sobol) quasi-random sequences in Python/SciPy? and https://github.com/naught101/sobol_seq

I want to use the generated values in monte carlo simulations. Any help is appreciated.




How do I convert an internal

I'm trying to convert an internal HTML script element into an external Javascript file. The element works perfectly in HTML, but I don't understand what I need to change in order for it to work from an external Javascript file. What I have right now "fires" - it does generate the random images - but it shows them full screen, blocking off the entire website.

Here is the working HTML


 <script class="randomad" type="text/javascript">
            var total_images = 7;
            var random_number = Math.floor((Math.random()*total_images));
            var random_img = new Array();
            random_img[0] = '<a href="http://www.antares-sellier.com/en/"><img src="javascript/js_images/antares.jpg"></a>';
            random_img[1] //....1-5 excluded here for brevity//
            random_img[6] = '<a href="http://www.scesports.org/"><img src="javascript/js_images/sces.jpg"></a>';
            document.write(random_img[random_number]);
            </script>

In the HTML file, I've replaced the script element with:

           <div id="firstads"></div>

and added

<script src="javascript/rec_images.js" async></script> 

to the head element.

In Javascript, I've removed the script tags and added a function, but I'm pretty new to Javascript and can't figure out what else I need to add or change to make the conversion work properly

Here is the malfunctioning Javascript code:

window.onload = random_ad;

 function random_ad () {
     document.getElementById("firstads");
    var total_images = 7;
    var random_number = Math.floor((Math.random()*total_images));
    var random_img = new Array();
    random_img[0] = '<a href="http://www.antares-sellier.com/en/"><img src="javascript/js_images/antares.jpg"></a>';
//....1-5 excluded here for brevity//
    random_img[6] = '<a href="http://www.scesports.org/"><img src="javascript/js_images/sces.jpg"></a>';
    document.write(random_img[random_number]);

 }

The goal is to have a hyperlinked image randomly generated in by an external javascript file. The images need to be small enough to fit in an aside column, but right now they are the size of the browser. I'd really appreciate any help with fixing this!




How generate multiple UUID based on quantity field?

I'm having trouble adapting this Snippet to Gravity Forms. This Snippet works as follows:

Each entry generates a unique ID (UUID) based on Snippet's default settings.

Original Code:

            add_filter("gform_field_value_uuid", "get_unique");

            function get_unique() {
                $prefix = "SLP2017-"; // update the prefix here 
                do {
                    $unique = mt_rand();
                    $unique = substr($unique, 0, 8);
                    $unique = $prefix . $unique;     
                }
                while (!check_unique($unique));
                return $unique;
            }
            function check_unique($unique) {
                global $wpdb;
                $table = $wpdb->prefix . 'rg_lead_detail';
                $form_id = 1; // update to the form ID your unique id field belongs to
                $field_id = 10; // update to the field ID your unique id is being prepopulated in
                $result = $wpdb->get_var("SELECT value FROM $table WHERE form_id = '$form_id' AND field_number = '$field_id' AND value = '$unique'");
                if(empty($result))
                    return true;
                return false;
            }

What I'm trying to do is this:

Generate 'X' UUID based on the quantity field (other field) of gravity forms.

Example: The value of the field quantity is 20 so the Snippet has to generate: 20 differents UUID.


However in my attempts with "FOR" the maximum I could do was to generate a two different UUIDs but only returning the echo and not registering the UUIDs in the database and for some reason does not return the quantity that I put, in the example below I put 10 and it only returns me 2.

My Code:

            add_filter("gform_field_value_uuid", "get_unique");

            function get_unique() {
                $prefix = "SLP2017-"; // update the prefix here
                $quantity = 10; //quantity test to generate two diffente UUID's     
                do {
                    $unique = mt_rand();
                    $unique = substr($unique, 0, 8);
                    $unique = $prefix . $unique;
                    for($x = 1; $x < $quantity; $x++){
                       $unique;
                    }
                    echo $unique . ' | ';        
                }
                while (!check_unique($unique));
                return $unique;
            }
            function check_unique($unique) {
                global $wpdb;
                $table = $wpdb->prefix . 'rg_lead_detail';
                $form_id = 1; // update to the form ID your unique id field belongs to
                $field_id = 10; // update to the field ID your unique id is being prepopulated in
                $result = $wpdb->get_var("SELECT value FROM $table WHERE form_id = '$form_id' AND field_number = '$field_id' AND value = '$unique'");
                if(empty($result))
                    return true;
                return false;
            }

If any good soul can help me, I appreciate so much :)