dimanche 30 juin 2019

Raw binary stream for dieharder using Matlab

I would like to use dieharder library to test a generator I made in Matlab.

According to the man page, we can use a raw binary stream as input for the dieharder function, like so :

cat /dev/urandom | ./dieharder -a -g 200

So, if I assume my random number generator is located in the function "generator.m", what command should I use?

Moreover, according to this question, I can't just use a "fprintf('%d')" function in Matlab to use the Dieharder library. In Python they are using the struct class, do you know what I should use in Matlab?




Python- generating random list of fruits

I need help with a problem: Your task is to build a program that randomly recommends a different kind of one type of fruit each day. The user should be able to pick from a menu of at least three different kinds of fruit (banana is a required selection). The program should also randomly select a new fruit variant for all 30 days of a month. For example, I should be able to choose between: banana, apple, and kiwi. I will select kiwi. It will then produce a randomly selected list of 30 different types of kiwi and present them in a list. If I run the program again and select kiwi, then it will return a new list of kiwi.
It needs to have randomly selected list (which I already created the list), and all 30 days of the month.

I have created a Fruit class and an input statement for the user but am stuck.

from random import randrange

class Fruit:
    def __init__(self, banana, apple, kiwi):
        self.banana=banana
        self.apple=apple
        self.kiwi=kiwi



def main():
    userInput=input("Enter the type of fruit:  ")




How to compute random bfloat number in Maxima CAS

Maxima Cas random function takes as an input floating point number and gives floating point number as an output.

I need floating point number with more digits, so I use bfloat with increased precision.

I have tried :

random(1.0b0)
bfloat(random(1.0));

The best result was :

(%i11)  :bfloat(%pi)/6.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b0
(%o11) 5.235987755982988730771072305465838140328615665625176368291574320513027343810348331046724708903528447b-1

but it is not random.




Sampling from a given region

I am exploring a way to sample from the following region on a two dimensional coordinate (the blue region):

enter image description here

Of course, the baseline is that I can sample random number (x,y) and then check if it overlaps with the smaller box or outside the larger box. But that just wastes too many computing resource, after some quick trial.

Any suggestion or advice will be appreciated, thank you.




Shuffle function for list in a list

Trying to append two lists and shuffle elements of both lists simultaneously with one enumerate function

I am using two functions: 1) appending list_b to list_a 2)shuffling list_a and giving using enumerate function to do indexing.

In addition, I also want to shuffle elements of list_b within the new shuffled list_a and use same enumerate function to index items of both lists in a same number sequence. Below is where I stand so far. Thanks for help

list_a = ["alpha","beta","romeo","nano","charlie"]
list_b = [1,2,3,4,5,6,7]
from random import shuffle
list_a.append(list_b)
shuffle(list_a)
print(list_a)

for idx, val in enumerate(list_a, start=1):
    print(idx, val)

Output

['nano', 'charlie', 'alpha', 'beta', [1, 2, 3, 4, 5, 6, 7], 'romeo']

1 nano
2 charlie
3 alpha
4 beta
5 [1, 2, 3, 4, 5, 6, 7]
6 romeo




How do you switch 2 elements in the same array?

I am trying to shuffle a non shuffled deck(2D array) that i have created earlier in the same class under a function named NewDeck(). The code is designed to switch two elements in the same array thousands of times and get a unique deck with no duplicates. Instead it returns 52 deck of the same card.

Thanks

Code:

public static string[,] Shuffle()
    {
        Deck cDeck = new Deck() { shuffledDeck = Deck.NewDeck() };
        Random rnd = new Random();

        int x, y, z, k;

        string[,] ph = cDeck.shuffledDeck;

        for (int i = 0; i < 10000; i++)
        {
            x = rnd.Next(4);
            y = rnd.Next(13);
            z = rnd.Next(4);
            k = rnd.Next(13);

            cDeck.shuffledDeck.SetValue(ph[x, y], z, k);
            cDeck.shuffledDeck.SetValue(ph[z, k], x, y);
            ph = cDeck.shuffledDeck;
        }
        return cDeck.shuffledDeck;
    }




Generate a random string excluding certain special characters in python

I just started learning coding. I was trying to create a password generator in python. After researching this website, I found that I can use,

random.SystemRandom().choice(string.punctuation)

My question is, How can I generate random characters from the set of punctuation excluding the special characters '#$~' etc?

s=random.SystemRandom().choice(string.punctuation)

I would like my variable s to have random special characters excluding a few of my choice.




samedi 29 juin 2019

Is there a way i can generate multiple datasets using the numpy random number generator from a distribution

I am attempting to generate multiple random datasets (50) of a normal distribution with 100 random numbers using different seeds in the random number generator for each dataset. And then plot all 50 samples on the same graph

I can do this for one data set but not sure how to achieve this for 50 different random generators in a single code

import numpy as np
import matplotlib.pyplot as plt
seed = 15
r=np.random.RandomState(seed)
data=r.normal(size=100)  # length= 100
plt.plot(data)
plt.show()




Python generate multiple random matrices in a for loop

I am trying to generate multiple (#: 100) random column stochastic matrices using a for loop and save them.

Below code is to generate an individual random column stochastic matrix.

import numpy as np
import random

a = 2
sto = np.I(2)
sto = sto + np.random.uniform(low=0.3, high=.2, size=(a, a))
sto = sto/sto.sum(axis=0, keepdims=1)
print(sto)

When I try to implement the operation to generate 100 matrices with a for loop I fail - all matrices generated turn out to be the same.

How can I use the for loop to generate such matrices and save them all for later work?




Create chance function in rpg game

I am creating a server-side RPG game that has a chance system. for example, the player has a 30% chance when hit target stuns the enemy and 70% percent to 35% more damage.

so I come with this solution.

//'s' as stuns and 'd' as more damage;
array a = ['s', 's', 's', 'd', 'd', 'd', 'd', 'd', 'd', 'd'];
int chance = random(0, 9);
print a[chance];

but the above solution has a problem first it only works with an Integer number and another is that only work with a number that can be divided by 10.

for example, the above function that's not going to work with 25% or 0.1% chance as input.




Weighted random sampling for Monte Carlo simulation in R

I would like to run a Monte Carlo simulation. I have a data.frame where rows are unique IDs which have a probability of association with one of the columns. The data entered into the columns can be treated as the weights for that probability. I want to randomly sample each row in the data.frame based on the weights listed for each row. Each row should only return one value per run. The data.frame structure looks like this:

ID,    X2000,  X2001,  X2002,  X2003,  X2004
X11,   0,      0,      0.5,    0.5,    0
X33,   0.25,   0.25,   0.25,   0.25,   0
X55,   0,      0,      0,      0,      1
X77,   0.5,    0,      0,      0,      0.5

For weighting, "X11" should either return X2002 or X2003, "X33" should have an equal probability of returning X2000, X2001, X2002, or X2003, should be equal with no chance of returning X2004. The only possible return for "X55" should be X2004.

The output data I am interested in are the IDs and the column that was sampled for that run, although it would probably be simpler to return something like this:

ID,    X2000,  X2001,  X2002,  X2003,  X2004
X11,   0,      0,      1,      0,      0
X33,   1,      0,      0,      0,      0
X55,   0,      0,      0,      0,      1
X77,   1,      0,      0,      0,      0




vendredi 28 juin 2019

Generate n-dim random samples based on empirical distribution and copula

I am given an empirical distribution $F^{\text{emp}}_{X}$ of a real-valued random variable $X$. Given now $X_1,\ldots,X_n$ having the same distribution as $X$ and dependencies given by a copula $C$. I would like now to produce random samples of $(X_1,\ldots,X_n)\in\mathbb{R}^n$ with R.

E.g. I am given a vector of samples and the corresponding cdf

x<-rnorm(1000)
df<-ecdf(x)

Assume that I pick for a example a t-student or Clayton copula $C$. How can I produce random samples of for example 10 copies of $x$, where their dependency is determined by $C$.

Is there an easy way? Or are their any packages that can be used here?




How to add random numbers together. Python

number_checker = 0

for random_variables in range(1,11):  
    import random  
    random = random.randint(1,25)  
    print(random)  
    if random % 2 == 0:  
        print("This number is even")  
        even_numbers = number_checker + random  
    else:  
        print("This number is odd")  
        odd_numbers = number_checker + random    

print("")  
print("This is the sum of even numbers.")  
print(even_numbers)  
print("")  
print("This is the sum of odd numbers.")  
print(odd_numbers)  

Sorry about the formatting this is my first time using Stack Overflow.




ACF repeater random order

I have ACF repeater and showing one field on each page load using array_rand(), but I need the fields to be shown one by one in the order (row 1, row2, row 3), so randomness but by order. This is what I have now, and can't get how to make this order.

if ( get_field('random_non-random') == 'random' ) {
      echo '<div class="all-featured-image landing">';
      $rows = get_field('random_featured_image' );
      $rand_row = $rows[ array_rand( $rows, 1 ) ];
      $rand_row_image = $rand_row['featured_image'];
      $image = wp_get_attachment_image_url( $rand_row_image, 'full' );
      echo '<img src=" ' . $rand_row_image['url'] .' " alt="' . $rand_row_image['alt'] .'" title="' . $rand_row_image['title'] .'">' ;    
      echo '</div>';    
    }

Seems like I need to use count($rows) somewhere?




How can I make an if and elif statement based on an outcome of random.choice and an input

I am trying to create a game that asks you what a certain character does in a book and I am using random.choice and an if and elif statement to do that however when I type my input to answer the question the output is always wrong even though i answered the question wright.

I have tried to make the if statement:

if 'The main character' in card_list and choice == person1:
  print("correct")

for every statement however the results are always correct even if i type in the wrong answer.

import random

card1 = 'The main character'
card2 = 'He brings aleem on holiday'
card3 = 'Dies in the middle of the book'
card4 = "She takes care of aleem while aleem's dad is in Ethiopia"
card5 = 'He helps take care of aleem with Miss Fitzgerald'
card6 = "He is in charge of aleem's court case"

person1 = 'aleem'
person2 = "aleem's dad"
person3 = "aleem's mum"
person4 = 'Miss Fitzgerald'
person5 = 'Mr Fitzgerald'
person6 = 'Nicolas'

card_list = [card1, card2, card3, card4, card5, card6]

print(random.choice(card_list))

choice = input('Who is this? ')

if 'The main character' == random.choice and choice == person1:
  print("correct")
elif 'He brings aleem on holiday' == random.choice and choice == 
person2:
  print('correct')
elif 'Dies in the middle of the book' == random.choice and choice == 
person3:
  print('correct')
elif "She takes care of aleem while aleem's dad is in Ethiopia" == 
random.choice and choice == person4:
  print('correct')
elif 'He helps take care of aleem with Miss Fitzgerald' == 
random.choice and choice == person5:
  print('correct')
elif "He is in charge of aleem's court case" == random.choice and 
choice == person6:
  print('correct')
else:
  print('wrong')

This is what I have been using to create the game.




Encountering "Fatal error: Index fell out of range" error when random number is generated

I'm trying to create a bingo number generator app, however after generating numbers "Fatal error: Index fell out of range" was encountered randomly on line "let letter = prefixes[bingoBall/15]".

var numbersSeen = Set<Int>()
var prefixes = ["B-", "I-", "N-", "G-", "O-"]

func randomNumber() -> Int {

    var nextNum : Int
    repeat {
        nextNum = Int.random(in: 1...75)

        if !numbersSeen.contains(nextNum) {
            numbersSeen.insert(nextNum)
            return Int(nextNum)
        }

    } while true
}

func randomBall() {
    let bingoBall = randomNumber()
    let letter = prefixes[bingoBall/15]
    lblNumber.text = "\(letter)\(bingoBall)"

    lblNumCalled.text = String(numbersSeen.count) + " numbers called."
    lblNumRemain.text = String(75 - numbersSeen.count) + " numbers remaining."

    if lblNumPrev.text != "" {
        lblNumPrev.text = lblNumPrev.text!+", "+lblNumber.text!
    }else{
        lblNumPrev.text = lblNumber.text!
    }
}




Random values in iterative cte's

Using SqlServer 2016+

I have been having some difficulty in selecting random rows from a table which has been narrowed down to an issue with how random numbers are generated. For efficiency using a TOP 10 * ORDER BY NEWID() is to slow. In the code below I have used a set seed for repeatable results, but in live I would not.

Code Sample:

SELECT  RAND(100) RN
,       RAND()
,       RAND()
,       RAND()
,       RAND();

SELECT  RAND(100) RN
UNION ALL SELECT  RAND()
UNION ALL SELECT  RAND()
UNION ALL SELECT  RAND()
UNION ALL SELECT  RAND();

WITH cte AS
    (SELECT 1         ID
     ,      RAND(100) RN
     UNION ALL
     SELECT cte.ID + 1
     ,      RAND()
       FROM cte
      WHERE ID < 5)
SELECT  RN
  FROM  cte;

Result Set

RN                                                                                          
---------------------- ---------------------- ---------------------- ---------------------- ----------------------
0.715436657367485      0.28463380767982       0.0131039082850364     0.28769876521071       0.100505471175005

(1 row affected)

RN
----------------------
0.715436657367485
0.28463380767982
0.0131039082850364
0.28769876521071
0.100505471175005

(5 rows affected)

RN
----------------------
0.715436657367485
0.28463380767982
0.28463380767982
0.28463380767982
0.28463380767982

(5 rows affected)

As you can see from the results when I call the RAND() function repeated in-line or via a union I get different results with each call. If however I call the function inside an iterative cte then I get the same value repeated.

This code is an example showing the problem, rather than the entire code set. I have created this purely as an example to demonstrate the problem. I have a solution based around a combination of Checksum & NewID() and the modulus calls and multiplication to give me values in the range I want, but this is fairly complex and seems excessive for just generating a list of random numbers in a range.

I'm looking for any guidance that can be offered on

  1. Why this is happening
  2. Any ways to solve the issue
  3. Other options for generating lists of random numbers (That aren't RBAR)

Many thanks.




jeudi 27 juin 2019

How to define 'marginal distribution' in GenOrd package?

I'm trying to generate ordinal correlated variables with GenOrd package. However, there are some problems.

I'm getting help on this page, which was written by Wesley

https://www.r-bloggers.com/simulating-random-multivariate-correlated-data-categorical-variables/

In this page, and most of other explanation about GenOrd package, the marginal distirbution must be set. In this page, the marginal distribution is

#The values are cumulative so for the first variable the first marginal will be .1, the second is .2, the third is .3, and the fourth is .4
marginal <- list(c(0.1,0.3,0.6),c(0.4,0.7,0.9))
> marginal
[[1]]
[1] 0.1 0.3 0.6

[[2]]
[1] 0.4 0.7 0.9

However, as far as I Know, the marginal distribution is as follows. (from English wikipedia)

enter image description here

So the sum of marginal probability is 1. However, in the second list in marginal object, the sum is 0.4+0.7+0.9=2

How can I interpret this object?




Generating N random numbers from rand2()

Can someone explain the logic in for loop? how it is generating random numers

int rand2()
{
    return rand() & 1;
}

int randn(int N)
{

    int add = 0;
    int ref = 1;

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

        add = add + rand2() * ref;

        ref = ref * 2;
    }

    return add % N;
}

int main()
{
    srand(time(NULL));
    printf("%d, ", randn(5));

    return 0;
}




Generate random numbers with equal probability

Can someone please explain what's going on in for loop in this code snippet?

int rand7() {
    int sum = 0;
    int multiplier = 1;
    for (int i = 0; i < 7; i++) {
        sum = sum + rand5() * multiplier;
        multiplier = multiplier * 5;
    }
    return sum % 7;     
}




Random selection with conditional probabilities

I have list say y = [1, 2, 3, 4, 6, 7, 8, 9, 5, 23, 12, 24, 43, 10] and I want to make random selection from it with conditional probability. A number greater than 10 in the list has a probability of say 0.8 of being selected while the rest have probability 0.2 of being selected.




Using random numbers vs hardcoded values in unit tests

When I write tests, I like to use random numbers to calculate things.

e.g.

 func init() {
   rand.Seed(time.Now().UnixNano())
 }

  func TestXYZ(t *testing.T) {
     amount := rand.Intn(100)
     cnt := 1 + rand.Intn(10)
     for i := 0; i < cnt; i++ {
       doSmth(amount)
     }
     //more stuff
  }

which of course has the disadvantage that

expected := calcExpected(amount, cnt)

in that the expected value for the test needs to be calculated from the random values.

If have received criticism for this approach:

  • It makes the test unnecessarily complex
  • Less reproduceable due to randomness

I think though that without randomness, I could actually:

  • Make up my results, e.g. the test only works for a specific value. Randomness proves my test is "robust"
  • Catch more edge cases (debatable as edge cases are usually specific, e.g. 0,1,-1)

Is it really that bad to use random numbers?

(I realize this is a bit of an opinion question, but I am very much interested in people's point of views, don't mind downvotes).




How to use current time in seed number of ELM random

Random seed in Elm programming. If I use fixed seed I will get same random number. How can I use current time in seed number? I am using Elm 0.19.

Random.initialSeed <currentTime>

So - how to get current time or start time to ?




Permanently set seed in python

I have read several questions including those aimed specifically at numpy. I am however simply interested in permanently setting seed in(with) random and hence generate the same random float with random.random() with each call. Here's what I did:

import random
random.seed(2) 

First call:

random.random()
0.9560342718892494

Second call:

random.random()
0.9478274870593494


I could keep calling random.seed but would appreciate if someone could explain what is going on or what exactly I can do to set seed once and generate the same random float with each random.random() call.

I am currently trying to learn python so my apologies if this is very basic and already has an answer. I have read several questions before posting.




mercredi 26 juin 2019

How to select n chunks randomly from a dataset

I have 100 chunks of samples at which each chunk has 100 elements. The elements in one chunk are 5 seconds apart; However the time difference between the elements from different chunks is 5 hours at least (not fixed time). My main goal is to pick 10 chunks from the dataset Randomly .

My dataset:

index     time                  value   
i       12-1-2019 05:22:43       12         }  Chunk 1
i+1     12-1-2019 05:22:48       13
i+2     12-1-2019 05:22:53       14
..
i+99  ...............................

i+x      12-1-2019 13:32:12      31         }  Chunk 2
i+x+1    12-1-2019 13:32:17      77
i+x+2    12-1-2019 13:32:22      16
..
i+x+99  ...............................

i+x      14-1-2019 23:45:43      14         }  Chunk 3
i+x+1    14-1-2019 23:45:48      57
i+x+2    14-1-2019 23:45:53      46
..
i+x+99  ...............................

Note: the chunks are ordered (i.e: Chunk 1 occurred before chunk 2 that occurred before chunk 3 and so on).

I would like to pick 10 chunk of 100 randomly. However, the order of the elements in the chunk is important and can't be shuffled.




How to check and extract the url containing the random number with the status code

import string
import random
import requests

_LENGTH = 5 
string_pool = string.digits
result = ""
for i in range(_LENGTH):
    result += random.choice(string_pool) 

url = "http://bbs.blabla.com/" + result
response = requests.get(url)

if response.status_code = 200:
    print(url)

Based on the following function, How do I code to identify and extract accessible URLs with status codes? I want to know both how to extract all URLs and how to extract first URL. I would really appreciate it if you let me know the code including multiprocessing.




Reproducible random tests

I've recently run into the following piece of documentation. A cursory search revealed just a gist. So I decided to bring these ideas to life.

The first one is far from being used as is. The second one is too wordy and doesn't work in case of failure (failureException is supposed to be a class, the corresponding method can be commented out).

Before I describe my solutions, let me ask the questions. 1. Am I doing anything wrong? This sort of task must have been simplified ages ago. At least in my book. 2. Is there any way to improve my solutions?

The first one (branch factory-boy-state) stores random generators' state in files, that can later be used to pass state to the tests:

class MyTestRunner(DiscoverRunner):
    def setup_test_environment(self):
        self.handle_rnd_state(faker.generator.random, 'faker.state',
            'FAKER_RANDOM_STATE')
        self.handle_rnd_state(factory.random.randgen, 'factory.state',
            'FACTORY_RANDOM_STATE')
        super().setup_test_environment()

    def handle_rnd_state(self, rnd, fname, env_var):
        state = self.retrieve_rnd_state(fname, env_var)
        if state:
            rnd.setstate(state)
        else:
            self.store_rnd_state(fname, rnd.getstate())

    def retrieve_rnd_state(self, fname, env_var):
        state = os.environ.get(env_var)
        return pickle.loads(b64decode(state.encode('ascii'))) if state else None

    def store_rnd_state(self, fname, state):
        encoded_state = b64encode(pickle.dumps(state))
        with open(fname, 'w') as f:
            f.write(encoded_state.decode('ascii'))

Usage:

$ ./manage.py test --testrunner p1.tests.MyTestRunner
$ FAKER_RANDOM_STATE=`cat faker.state` FACTORY_RANDOM_STATE=`cat factory.state` ./manage.py test --testrunner p1.tests.MyTestRunner

Another one (branch factory-boy-seed) seeds the random generators, but the seed can be overriden via an environment variable:

class MyTestRunner(DiscoverRunner):
    def setup_test_environment(self):
        seed = os.environ.get('FACTORY_SEED')
        if seed:
            seed = seed.encode('ascii')
        if not seed:
            seed = b64encode(os.urandom(16))
        print('-- seed: %s' % seed.decode('ascii'))
        factory.random.reseed_random(seed)
        super().setup_test_environment()

Usage:

$ ./manage.py test --testrunner p1.tests.MyTestRunner
$ FACTORY_SEED=IPnHCxdWehAxz6ctbNvyPQ== ./manage.py test --testrunner p1.tests.MyTestRunner

Test runner can be put into the settings.




Making Random Choices from multiple lists effectively

I'm implementing Wilson's Algorithm, which uses random walks along graphs. So, at every step, I currently do run random.random.choice on the list of neighbors of my current vertex. However, this is obviously slow. If I was making random choices from the same list repeatedly, I could use numpy's np.random.choice with a larger size, but since the length of neighbors is not the same for all vertices, I am not sure how to do this.




I wish to know how do we set session with function instead of assigning values

How do I fix these random values so that it remains the same till 12 hours. This is getting changed each time the page is refreshed.

This is my code assigning random numbers to a section

function getRandomNumber(minNumber, maxNumber) {
  return Math.floor(Math.random() * (maxNumber + 1) +
    minNumber);
}

getRandomNumber();

$('.someclass').each(function() {
  var x = $(this);
  const y = $(.sproof); //sproof is the snippet where the value 
  is being inserted //
  y.insertAfter(x.find('.someclass2'));
});

$('.someclass3').each(function() {
  var minNumber = 700;
  var maxNumber = 701;
  $(this).html(getRandomNumber(minNumber, maxNumber));
});

$('.someclass3').each(function() {
  var minNumber = 700;
  var maxNumber = 701;
  $(this).html(getRandomNumber(minNumber, maxNumber));
});

The random number needs to be the same throughout the day even after refresh. My case is that the numbers are generated each time the page is refreshed.




Math.random() with do while loop sometimes hang the page

I am making a simple game where I need to generate an object 1: its position x and y needs to be in certain range 2: it must not overlap with some existing objects. I use the Math.random() and the do while loop for that, but the game intermittently crashes.

I cannot see any flaw in the logic, but why it crashes?

 let posX, posY;
 let invalid = false;
     do {
         posX = getRandomInt(0,100);
         posY = getRandomInt(0,100);
         if (posX > 20 &&
             posX < 40 &&
             posY > 20 &&
             posY < 40
            )
              invalid = true;
        }
        while (invalid)
 alert("not crash!")
 function getRandomInt(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }



How to randomly select 3 elements and remove them from the array? (Javascript)

I need help with a function to select 3 random elements within an array, and to remove them from the array.




mardi 25 juin 2019

I cannot get my program to stop repeating my first statement

Python just keeps repeating back to me "How many random numbers do you want?" and won't move on to the next input.

I've tried most things I could think of.

do_program = True while(do_program): while(True): try: number_of_numbers = float(input("How many random numbers do you want?")) if(number_of_numbers < 0): print("Negative numbers are not allowed.") continue except ValueError: print("The value you entered is invalid. Please enter numerial values only.") else: break

while(True):
    try:
        lowest_number = float(input("What is the lowest random number you want?"))
        if(lowest_number < 0):
            print("Negative numbers are not allowed.")
        continue
    except ValueError:
        print("The value you entered is invalid. Please enter numerial values only.")
    else:
        break

while(True):
    try:
        highest_number = float(input("What is the highest random number you want?"))
        if(highest < 0):
            print("Negative numbers are not allowed.")
        continue
    except ValueError:
        print("The value you entered is invalid. Please enter numerial values only.")
    else:
        break
import random
print("The numbers were written to randomnum.txt.")

def main():
    for count in range(number_of_numbers):
        number = random.randint(lowest_number, highest_number)
        print(number)
main()

Right now I just want to focus on getting to my second and third input statements.




Random String in Bash Script [duplicate]

This question already has an answer here:

I am trying to play a random .wav file from the command line. The files are called 1.wav, 2.wav, .... 10.wav

I have created the following .sh script and given it the appropriate execution rights:

#!/bin/sh
rnd=$((1 + RANDOM % 10))
cmd="aplay -D default:CARD=Device ./$rnd.wav"
echo $cmd

and it always returns

aplay -D default:CARD=Device ./1.wav

What am I missing? Thanks for your help!




Generate normal random variable and sample

Generate 3 normal random variables with mean 100 and standard deviation 1. This will require 3 lines of code.

Import the numpy library Set the seed to 123 to initialize environment so random variables are replicated according to the grader. (hint: np.random.seed(?)) Draw three random normal variables with mean 100 and standard deviation 1 and assign it to a variable named sample. (hint: np.random.normal(?,?,?)) Print sample.




Randomize numpy.argsort output in case of ties

I have a numpy array with some elements same as others i.e. there are ties, and I am applying np.argsort to find the indices which will sort the array:

In [29]: x = [1, 2, 1, 1, 5, 2]

In [30]: np.argsort(x)
Out[30]: array([0, 2, 3, 1, 5, 4])

In [31]: np.argsort(x)
Out[31]: array([0, 2, 3, 1, 5, 4])

As can be seen here, the outputs we get by running argsort two times are identical. However, array([2, 3, 0, 5, 1, 4]) is also a completely valid output because some elements in the original array are equal. Can I make argsort return me such "randomized" outputs when there are ties in my array? If not, what is a workaround because I don't want to bias my choice of the lowest values in the array when I am picking them.




How to randomize names without repeating its name in a row when you click again the randomize function?

Good day. I am making a program to send monthly survey for IT employees with 46 members. Given the code in google app script in google sheet, how could I limit the names of ratees to appear again on the same row when I run randomize function in the 2nd to 6th times. Thank you.

Requirement:
Given the data below, ratee 1-5 should not appear again in the same row when you run randomize function 2nd-6th times.

Data Data

 function randomize() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheetname = "Emails";
      var sheet = ss.getSheetByName(sheetname);

      // some variables
      var randomcount = 2; // how many random names
      var rowstart = 2; // ignore row 1 - the header row
      var width = 6;    // how many names in each row - 1/rater plus 5/ratee
      var thelastrow = sheet.getLastRow();
      //Logger.log("DEBUG:last row = "+thelastrow)

      // get the employee names
      var employeecount = thelastrow-rowstart+1;
      //Logger.log("DEBUG: employee count = "+employeecount);//DEBUG

      // get the data
      var datarange = sheet.getRange(rowstart, 3, thelastrow - rowstart+1);
      //Logger.log("DEBUG: range = "+datarange.getA1Notation());//DEBUG
      var data = datarange.getValues();
      //Logger.log("data length = "+data.length);
      //Logger.log(data); 

    var data1d = data.map(function(e){return e[0]});
    var finalArr = getRandUniqMatrix(5, 46).map(function(row){return row.map(function(col){return data1d[col]})}); 
    sheet.getRange(2,4,finalArr.length, finalArr[0].length).setValues(finalArr);

    }

    function getRandUniqMatrix(numCols, numRows) {

      var maxIter = 1000; //Worst case number of iterations, after which the loop and tempCol resets
      var output = Array.apply(null, Array(numRows)).map(function(_, i) {
    return [i++];
      });//[[1],[2],[3].....]
      var getRandom = function() {
    return Math.floor(Math.random() * numRows);
      };//getrandom number within numRows
      while (numCols--) {//loop through columns
    for (
      var row = 0, currRandNum = getRandom(), tempCol = [], iter = 0;
      row < numRows;
      ++row
    ) {//loop through rows
      //unique condition
      if (!~output[row].indexOf(currRandNum) && !~tempCol.indexOf(currRandNum)) {
        tempCol.push(currRandNum);
      } else {
        currRandNum = getRandom();//get a new random number
        --row;
        ++iter;
        if (iter > 1000) {//reset loop
          iter = 0;
          tempCol = [];
          row = -1;
        }
      }
      if (row + tempCol.length + 1 === numRows * 2) {//last row, Combine output+tempCol
        output.forEach(function(e, i) {
          return e.push(tempCol[i]);
        });
      }
    }
      }
      return output;
    }
    console.info(getRandUniqMatrix(5, 46));

Expected outcome:

Totally different names per row of ratees when you run randomize function in the 2nd,3rd,4th,5th and 6th times.




lundi 24 juin 2019

How do I use lists to randomize the order of stimulus presentation in E-Prime?

I am trying to present word stimuli for an experiment. Each word on the screen will pop up individually, and when the participant progresses to the next one, it will replace the previous word. I want the words to go in a certain order, with specific instances of randomization. For example, for one participant, the order should go as "cat -> dog -> bird", the second participant should see "cat -> dog -> lizard", and the third participant should see "cat -> wolf -> bird" or some similar variation. Is this possible to do in E-Prime 3.0, specifically using the List tool?

I am currently reading the documentation, but it does not provide a fix for my specific need.

I have tried changing the order of the words manually.

There is no specific code involved, as it is done through E-Prime is more of a "fill-in-the blanks" sort of thing.

Expected results: The order of words should be random. Actual results: The order of words is fixed, and will just proceed down the List until the experiment ends.




How generate random points within cylinder

how to generate uniformly distributed points within cylinders giving these parameters, Center point denoted as C, C1 is bottom and C2 is Top and R is Radius. C1=[5.697592e-01, 3.159923e-01, 1.037074e+00];C2=[4.211637e-01, 5.624242e-01, 7.937364e-02];R=5.000000e-01;

%the cordinate 
        C1=[5.697592e-01, 3.159923e-01, 1.037074e+00];
        C2=[4.211637e-01, 5.624242e-01, 7.937364e-02];
        N=600;
        CylinderX = rand(1,N);
        CylinderY = rand(1,N);
        CylinderZ = rand(1,N);
        CylinderHeight = norm(C1 - C2);

        for i = 1 : N
            A = [0 0 0 1];
            x = rand;
            y = rand;
            Px = sqrt(x)*R*cos(2*pi*y);
            Py = sqrt(x)*R*sin(2*pi*y);
            Pz = CylinderHeight * rand;
            %I need the coordinate transformation  logic here

            CylinderX(i) = A(1);
            CylinderY(i) = A(2);
            CylinderZ(i) = A(3);
        end
        plot3(CylinderX , CylinderY , CylinderZ ,'G.');hold on;




Permutate all posibilities for N lists with M length of middle array

I'm trying to carve some files. In order to do so, I'd like to permutate all possibilites. There are 3 possible beginnings, 40 possible middle blocks and 3 possible endings.

The problem is that we don't know how long the middle block is. It could be 1 block long but also 40 blocks longs. The only thing we know for sure is that the blocks appear consecutively since it is a PNG I'm trying to recover.

I already tried hand writing the code myself with a lot of for loops, without succes so far. I did try the following code.

s= [[headersList],[idatList],[iendList]]
    print(list(itertools.product(*s)))

I expect the output to be something like,

[1, [1], 1]
[1, [1,2] , 1]
[1, [1,2,3], 1]
...
[2, [1] ,1]
[2, [1, 2], 1]

And so on. The only condition is that the start and end block have to be on the corresponding beginning and ending of the array. The middle blocks have to be size 1 to max 40 in consecutive order.




dimanche 23 juin 2019

Can I call some method randomly in C# (Unity)?

I wanna call some method randomly. Can I do it in C#?

I tried to some trials like using array, but I failed.




How to generate dark shades of hex color codes in python

I am generating random different colors and generating like them below :

 import random
 import numpy as np

 random_number = np.random.randint(0,16777215)
 hex_number = str(hex(random_number))
 hex_number ='#'+ hex_number[2:]

But this generates mostly lighter shades and not dark ones. How can I modify this to generate darker shades.Any help is appreciated.




Impossible random numbers

Are there any numbers that Math.random() (either double or int) that java cannot produce?

(int)(Math.random()(max-min)+min); or Math.randmom()(max-min)+min;




Random string HTML escape issue, when using special chars

I was about to create a little javascript based tool, for quickly generating random strings, with, or w/o special chars and i found a nice snippet, which greatly inspired me: (https://stackoverflow.com/a/52464491/11689422):

function randStr(len) {
  let s = '';
  while (len--) s += String.fromCodePoint(Math.floor(Math.random() * (126 - 33) + 33));
  return s;
}

// usage
console.log(randStr(32));

This does the part of the job, when i want alphanumerical strings, with special chars too, but as soon, as i try to embed it into a HTML page, sometimes (actually, pretty frequently), the resulting string is randomly shorter, than the predefined length. It's ok though, when debugging in JS (the string's length is correct), but not on the html page, displayed with .innerHTML method). I also tried to use the following code, but the problem is the same:

function makeid(length) {
   var result           = '';
   var characters       = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&_-+=`|(){}[]:;\"'<>,.?/";
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   return result;
}

console.log(makeid(32));

Does anyone know a solution for this? Thanks a million in advance.




Select an object of a list, based on its attribute, and get the index of this object

I have two different lists (same size), say a and b. Both of them contain objects, and every object has the same attribute "Cost" (with different values, of course). I want to build a new list c, which containts randomly selected objects from a, e.g. by using random.choice() and then checking which of these objects in c has the highest value concerning it's attribute "Cost". But i also want to build a new list d, which containts a selection of the objects of b, which should NOT be selected randomly but with the same index of the one with the highest value from list c. And thats my problem.

I tried building a new list, say a1, with enumerate, so this list contains tuples with two elements: First the "index" and second the object. Then i generated the new list c by randomly selecting tuples from a1. I was also able to figure out which of these objects of c has the highest attribute using max(). But the output is just the object, and not the complete tuple including the "index". So since i don't know which index this object had, i can't choose the corresponding object of list b.

Here is an example:

a = [[1,2],[3,4],[5,6]]

Note: All three objects ([1,2] and [3,4] and [5,6]) have one attribute "Cost", which in this case is "10", "100" and "1000", respectively.

a1 = list(enumerate(x))
c = [random.choice(a1) for i in range(2)]

Now i want fo figure out which of the two objects in c has the highest value concerning the attribute "Cost". So i try this:

max([x[1] for x in c], key=attrgetter("Cost"))

This works, but i only get the object which has the highest value, in this case it's [5,6], and not the corresponding "index" (so the first item of the tuple), which in this case would be 2 (or 3, depending on where the enumerate() starts).

I found something like this:

max(c, key=itemgetter(1))[0]

But there it only checks the second item of the tuple (object), and not the value of the attribute corresponding to this object.

Any chance for solving this problem?




error null is not an object (evaluating RNRandomByte.seed) - ios

This error causes import crypto from "crypto"; the first mistake sounded like that "Secure random number generation is not supported by this browser. Use Chrom,Firefox or IE 11"

I performed the following steps https://github.com/mvayngrib/rn-nodeify

Android work Ios - error

https://github.com/mvayngrib/rn-nodeify

https://github.com/kimmimy/Food-Hunter.git . my prodject I'm just learning to work at RH

I look forward to a successful ios




How can I do "weighted" random number generation that favors some numbers over others, depending on user input?

First, I believe this is also maths based, so mods, if this is not the right place to address such a question, feel free to migrate it to a proper place. I am asking here, because I want this problem to be implemented in programming, specifically in c++.

Suppose the following scenario: - I want to RNG a number between 0 and 8 - there is an extra input taking in factor to the number being generated, to give better odds to certain numbers in this way (I'll try to be as clear as I can) :

If the user inputs '0', the number to be generated will have the following chance to come out:

'0' - weight of 5,
'1' - weight of 4,
'2' - weight of 3,
'3' - weight of 2,
'4' - weight of 1,
'5' - weight of 0,
'6' - weight of 0,
'7' - weight of 0,
'8' - weight of 0,

So that the chance of getting a random '0' is 5 times bigger than getting a '4', and it's zero chance to get '5', '6', '7' and '8'.

If the user inputs a '4', then the weights are as follow:

'0' - weight of 1,
'1' - weight of 2,
'2' - weight of 3,
'3' - weight of 4,
'4' - weight of 5,
'5' - weight of 4,
'6' - weight of 3,
'7' - weight of 2,
'8' - weight of 1

In this case, all the numbers have a chance to come out, but favoring the number '4' to be generated. Also, numbers '3' and '5' have the same chance of coming out, but yet, less probable than the number '4'.

And so on.

This can be translated into a weight table as the next picture shows:

Table of Weights image

Considering that I made myself clear (if not, please tell me! I'll try to explain it in a better way) about the problem, how can the solution to this problem be designed?

I am tagging c++ because that's the language I am learning, but this can be applied to any language in general.

Best regards!




samedi 22 juin 2019

Generate random values for different students in an assignment

I'm wondering if there is any website that a teacher can put in the HTML codes and then give students access to do the assignment, in which each value is different for each value? Say for one student, asset is $5 million, while for another, it's $10 million. Most variables are randomly generated, while some are built upon formulas of the other variables.

Please find my HTML code below, along with the variable definition.

This is for my mother - she's teaching accounting, but the school does not allow students to buy online programs like Wiley or Pearson.

<div class="narrative">

<p>Little Books Inc. recently reported $<alg:value>ni</alg:value> million of net income.  Its EBIT was $<alg:value>ebit</alg:value> million, and its tax rate was <alg:value>t</alg:value>%.  What was its interest expense?  [Hint: Write out the headings for an income statement and then fill in the known values.  Then divide $<alg:value>ni</alg:value> million net income by (1 - T) = <alg:value>t1</alg:value> to find the pretax income.  The difference between EBIT and taxable income must be the interest expense.  Use this same procedure to complete similar Problems.] Write out your answer completely. For example, 25 million should be entered as 25,000,000. Round your answer to the nearest dollar, if necessary.</p>


</div>

My variables:

var ni=integer(1,15);
var k=real(1.4,2.5,0.1);
var ebit=k*ni;
var t=integer(30,40,5);
var t1=1-0.01*t;
var ans=round((ebit-ni/t1)*100000000)/100;
lim ans>0;
lim ans = (ebit-ni/t1)*1000000;
# algorithm for feedback;
var NI1=ni*10^6;
var EBIT1=ebit*10^6;
var EBT=NI1/t1;
var Interest=EBIT1 - EBT;
var Tax=EBT*t/100;
var NI2=EBT- Tax;




How to get a random key

If I have the following:

var liststuff = {'key 1':'value 1', 'key 2':'value 2', 'key 3':'value 3'};

How should I go around to get a random key?

So the idea is that I would run a function and it will randomly give me one of the keys from liststuff, which I then could use to do what I want.

I though about giving 2 keys to each value, where the first one would be the 'key n', while the second key would be 'n-1' (n = number of keys):

e.g.

var belonging = {'Tom':'fish', 0:'fish', 'Jerry':'cheese', 1:'cheese', 'Billy':'pencil', 2:'pencil'};

And then I could do the following to get the random key:

let randChoice = Math.floor(3 * Math.random);
belonging[randChoice];

But then it would take too much space as the number of keys increases, and was wondering if there is a different and smarter way of doing this.




Numba and Numpy Random Number interaction

I am trying to generate a bunch of random numbers quickly to do a MCMC.

I have the following benchmarks:

@njit
def getRandos(n):
    for i in prange(n):
        a = np.random.rand()


%timeit np.random.rand(1000000000)
13.1 s ± 287 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit getRandos(1000000000)
1.97 s ± 25.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Clearly the parallelization improves my runtime. However, I don't know how the seeding of the random number generation works. How can I ensure that these numbers are truly random? Do I have to randomly choose a seed somehow?




is it possible to find relation between a single record(single row but multiple columns) of a data frame in python..?

Let's say the data has 4 columns(A, B, C, D) and 1 identifier column making a total of 5 columns. And every record in the dataframe is a different entity, so one row cannot be related to another.Lets say the size of the dataframe is 10x5(record_1, record_2 ....etc)

So now the task is to find a relationship between column A, B, C, D of record_1 (just one row). So is it possible .?




vendredi 21 juin 2019

Random in imacros

This code two years ago worked, but now shows error. I can not deal with it.

VERSION BUILD=1005 RECORDER=CR
SET !VAR1 EVAL("var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z']; var string = ''; for(var i = 0; i < 6; i++){string += letters[parseInt(Math.random() * 25)]}; string")
SET !VAR2 EVAL("var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z']; var string = ''; for(var i = 0; i < 6; i++){string += letters[parseInt(Math.random() * 25)]}; string")
SET !VAR3 EVAL("var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z']; var string = ''; for(var i = 0; i < 6; i++){string += letters[parseInt(Math.random() * 25)]}; string")
SET !VAR4 EVAL("var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z']; var string = ''; for(var i = 0; i < 6; i++){string += letters[parseInt(Math.random() * 25)]}; string")
SET !VAR6 EVAL("var letters = ['0','1','2','3','4','5','6','7','8','9']; var string = ''; for(var i = 0; i < 6; i++){string += letters[parseInt(Math.random() * 10)]}; string")
SET !VAR7 EVAL("var letters = ['0','1','2','3','4','5','6','7','8','9']; var string = ''; for(var i = 0; i < 2; i++){string += letters[parseInt(Math.random() * 10)]}; string")
SET !VAR8 EVAL("var letters = ['0','1','2','3','4','5','6','7','8','9']; var string = ''; for(var i = 0; i < 2; i++){string += letters[parseInt(Math.random() * 10)]}; string")
SET !VAR9 EVAL("var letters = ['0','1','2','3','4','5','6','7','8','9']; var string = ''; for(var i = 0; i < 9; i++){string += letters[parseInt(Math.random() * 10)]}; string")
SET !VAR5 EVAL("var letters = ['0','1','2','3','4','5','6','7','8','9']; var string = ''; for(var i = 0; i < 10; i++){string += letters[parseInt(Math.random() * 10)]}; string")

Error: BadParameter: Unsupported variable !VAR4, line: 5




Random numbers Python [duplicate]

This question already has an answer here:

I'm trying to build a program that will take random numbers from 2 dice.It should add them together. The user will input the desired number they want to reach. If the numbers from the dice are not equal to the number inputted by the user, it should loop around, do it again and count the number of times it took to get to the number inputted by the user. Currently the numbers loop and reach the desired number but the loops does not stop.

from random import randrange

statement =(input("This program rolls two 6-sided dice until their 
sum is a given target value. Enter the target sum to roll for:"))

diceOne = randrange(0,6)+1
diceTwo = randrange(0,6)+1
DiceSum = diceOne + diceTwo
Rollcount = 0

while DiceSum != statement:
    diceOne = randrange(0,6)+1
    diceTwo = randrange(0,6)+1
    DiceSum = diceOne + diceTwo
    printout = print('Roll:',(diceOne),'and', 
    (diceTwo),'equals'(DiceSum))




Function is unable to transform a list element if wrapped in a for function

Can someone explain the behavior of the following code?

import random


abc = ['a', 'b', 'c']
xyz = ['x', 'y', 'z']


def randomize(x):
    random.shuffle(x)
    x = x[0]
    print('expected: ' + str(x))
    return x


random_list = [abc, xyz]

for r in random_list:
    r = randomize(x=r)


print('-----\n')

print('actual: ' + str(abc))
print('actual: ' + str(xyz))

I would expect the return to match what is being printed in the function, however, that is not the case.




how to randomize the elements of a array in vhdl code?

I have a table with a known number of elements. I would like to randomize its elements so that each time I display it, its elements are displayed in random order. in vhdl using Fpga stratix3




create list with random values --> duplicates allowed [duplicate]

This question already has an answer here:

Please show me a solution that EXACLY answeres my question. If you show me a stackoverflow answered question that is 100% the solution of my question --> I will delete my question

need to create list with random int values like [1,2,3,4,3,2,5,6,7,4,..]. Duplicates are allowed!!!! All solution I found are

  1. creating lists with uniques
  2. using list comprehention..

There should be something like : list_randoms = random.sample(range(1, 10), 9) --> this creates list of uniqes.

Also listcomprehention/numpy/etc should not be the solution.

There should be a python build-in function for that which I cannot find now.

Not answered as I expect:

How do I generate a random list in Python with duplicates numbers

Generate Random List of Random Numbers with Duplicates in Python 3.4

Python: Random numbers into a list




jeudi 20 juin 2019

How to generate random utf-8 strings in JavaScript

I am seeking to creating a one line script that creates a string of a specified length with entirely random UTF-8 characters with some special characters excluded. I would like to avoid having a list all available UTF-8 characters.

The regex I would like all characters to match which appears to be PHP specific is: ^[\p{L}0-9]+

Doesn't match: %/.,@[^?!\$]+'`"

Matches: 漢字, зклмнпрстфхцчшщ, דזשודעזמאָ, فارسی

I have taken a look at randexp.js; however, trying my regex, possibly because it's PHP specific yields questionable results.

My question is two fold. What regex can I use in JavaScript to get the same results regex validation results? And how can I generate a random string of UTF-8 characters based off all available characters while still excluding some?




How would I loop generate random string of hex characters with a prefix in python?

This site is a good example https://textmechanic.com/text-tools/randomization-tools/random-string-generator/

I want to do that in python with a loop non-stop.




Two segment probability distribution

I need to generate random numbers in MATLAB for a parameter X that follows two-segment lognormal distribution as follows:

X(<= 20), median = 61, standard deviation = 1.33
X(> 20), median = 33.3, standard deviation = 0.605

Right now, I am alternately drawing one sample from each distribution. Then, I either accept or reject this sample, depending if it is less than equal to or greater than 20. Am I doing it correctly? If not, any suggestions will be helpful.




Filtering certain colors when using a random color generator that is seeded

Currently, I have a random color generated that I am pretty pleased with. The colors, for the most part, are appealing and the seeding data portion works as intended.

The problem is, I need to prevent the colors white and black from showing up. Actually, I would love to omit any shades of white, and any colors that are teetering on being black.

Here is my function:

    seededColorGenerator = (id, delivery_id) => {
        if (delivery_id) {
          return '#' + Math.floor((Math.abs(Math.sin(delivery_id) * 16777215)) % 16777215).toString(16)
        } else{
            return '#' + Math.floor((Math.abs(Math.sin(id) * 16777215)) % 16777215).toString(16)
        }
    }

I was thinking of explicitly picking out the color values and storing them into an array, then looping through them to check to see if said color was return and if so, call the algorithm again to get another random color. I am not sure that is the best practice for this.

Any ideas? I know there are plenty of conversations about random color generators, but I have yet to seen a good filtering process involved with them.




This line of code is supposed to generate exponential service times, but I am not able to get the logic behind it

This line of code is supposed to generate exponential service times, but I am not able to get the logic behind it.

% Exponential service time with rate 1 mean = 1; dt = -mean * log(1 - rand());

This is the source link, but MATLAb is needed to open the example.

I was also thinking if exprnd(1) will give the same result of generating numbers from the exponential distribution that has mean = 1?




Fastest precise normal RNG for CUDA

For simulations, I need to generate billions of normally-distributed random numbers in CUDA, while Box-Muller transformation is not an option (see here) because for floats it never produces numbers beyond +-5.7681074142 (thus it loses high-impact numbers with substantial probability). So curand is not an option because it uses Box-Muller transform (I've looked at the source code as of CUDA 10.0).

Now I am considering the following methods/algorithms:

  1. Marsaglia polar method
  2. Ziggurat algorithm
  3. Inverse transform sampling method
  4. Ratio-of-uniforms

Marsaglia polar and Ziggurat algorithms have loops, leading to thread divergence in CUDA warps. Thus it's hard for me to estimate how well they will perform in practice. Furthermore, the Ziggurat algorithm seems able to get initialized with different constants and I don't know how they affect precision and performance. Inverse transform sampling method seems to have a branch which will be followed by at least 1 thread in a warp usually, thus making all other threads to wait. Furthermore, I'm not sure about its precision - please, clarify. I haven't found comprehensive info on method #4 yet - please, clarify.

The underlying integer PRNG is xorshift+.

Having said the above, before going on and benchmarking all the above methods, I would like to ask you to:

  1. Mention other promising methods for CUDA that generate normally-distributed values (while such imprecise methods as Box-Muller is not an option).
  2. Give me some tips on how to implement some of the above or the other methods in CUDA.



Is there a way to create an array in java with some initialized numbers and then add random numbers to it

I am trying to create an array with 7 numbers that are manually inputted and 43 that random.

I am able to do it in C but I am facing a challenge in java the 7 numbers that are manually inputted keep coming out as zeros when the array is printed

int arr3[]= {1,2,3,4,5,6,7}; // this is where I created the array 
arr3=new int[50];

// this is where I tried to populate it

for (int i = 7; i < arr5.length; i++) 
{
arr3[i] = (int) (Math.random() * 1500);
} 

I would like the first few numbers to be manually inputted and the rest to be randomly created




Creating a MySQL table to map integer ID #s to random #s (2 column table, 1 w/ sequential #s, and another unique non-repeating larger random #)

Basically want to end up with a table of numbers from 1-500,000 in one column (sequentially), and a set of random larger numbers (say from 10000000-99999999) and have none of these duplicated.

Will be basically used to obfuscate the first number, and used as a 'lookup table', as the 2nd number will be the public facing one.




Unique random alphanumeric characters based on client ID

I would like to generate unique alphanumeric max 50 character string based on a client ID. What is the chance of getting the same string by the way? I have more than one client, I don't want strings to be overlapped.

Here is what I planning to use:

static Random _Random = new Random();
static char[] _AllowedChars =
            Enumerable.Range(48, 10).Select(x => (char)x)
                .Concat(Enumerable.Range(65, 26).Select(x => (char)x))
                .Concat(Enumerable.Range(97, 26).Select(x => (char)x))
                .ToArray();
static string PseudoUniqueString(int maxLength = 50)
            => new string(Enumerable.Range(1, Math.Max(1, maxLength))
                .Select(x => _AllowedChars[_Random.Next(_AllowedChars.Length)])
                .ToArray());

Is there a way to add client ID (let's say 1) at the beginning of this string? I don't come up with another solution. Advice needed.




vba get random with string as seed

I'm working under MS-Visio 2010 in VBA (not an expert) and I want to generate a random number (several numbers would be even better) based on a string as seed.

I know that Rnd(seed) with seed as a negative number exists. However, I don't know about any random generator with a string seed. Maybe some kind of hash function with a number as result ?

I'd like something like :

print function("abc")
45
print function("xyz abc-5")
86
print function("abc")
45

with spaces, symbols and numbers support when inside the seed string.

I may see a workaround by converting each character to some ascii number corresponding and somehow using this big number as seed with Rnd but it definitely feels far-fetched. Do anyone knows of a fancier way of doing so ?




mercredi 19 juin 2019

How to get a random element in a list for a loop in Python? [duplicate]

This question already has an answer here:

I want to get 2 elements from a list of 5 elements to iterate in a for loop in Python.

List = ["Item1","Item2","Item3","Item4","Item5",]

for item in List:
...Do Something...

I want random 2 items here and loop through only those two items.

ie. Item3 and Item5 randomly selected for the loop. Then loop ends.




Problem with generating random string and save into user meta field in wordpress

I've this code that doesn't want work. The code must create a random string of numbers and letters and add this as meta field of wordpress user. This code cause to User Add section errors like:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function myplugin_registration_save(), 1 passed in */class-wp-hook.php on line 286 and exactly 2 expected in /functions.php:347 Stack trace: #0 /wp-includes/class-wp-hook.php(286): myplugin_registration_save(51) #1 /wp-includes/class-wp-hook.php(310): WP_Hook->apply_filters(NULL, Array) #2 /plugin.php(465): WP_Hook->do_action(Array) #3 /user.php(1857): do_action('user_register', 51) #4 /user.php(226): wp_insert_user(Array) #5 */user-new.php(148): edit_user() #6 {main} thrown in ***/functions.php on line 347

(***/ hide the path)

the code:

function generateRandomString($length = 30) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

add_action('user_register', 'myplugin_registration_save', 10, 1 );
function myplugin_registration_save($user_id , $length) {
    $meta_key = "pkg_autologin_code";
    $timestampz=time();
    $tokenparta = generateRandomString();
    $key = $timestampz*3 . $tokenparta;
    update_user_meta($user_id, $meta_key , $key);
    }

Thankyou




How do I generate logscale random values between two numbers for hyper-parameter tuning i.e. learning rate?

For hyperparameters like learning rate, generating random numbers between 0.0001 and 1 will not provide an accurate representation of the hyperspace.

How would I generate 100 random numbers between 0.0001 and 1 with logscale?




(Random Selection) Names From A File

I am trying to make a random name generator method that will create a random first and last name from a list of names I have stored in two separate text files. (First Name.txt && LastName.txt)

So essentially I want to select a random token from the text file and match it from a random token from the last name text file:

I'm just not sure how I can manipulate the string names into a respective random integer.

private static void selectName(Scanner firstName, Scanner lastName) {
        // Initialization of Variables
    String randomFirstName = null;
    Random rand = new Random();
    int randomName = rand.nextInt(199) + 1; // 1 - 200

    while (firstName.hasNext()) {
        randomFirstName = firstName.next();
    }

} // closes FileInformation

The other idea I could think of was to store the contents into an array and transverse that way? Would that be the best way or is there a way to do it as I have now?




How to fill generated table with random values in JavaScript

I want to make application teamMaker, choose how many players and teams you need, then click button and application will generate table with random values with range from Player 1 - Value of input PlayersNum. My biggest problem is table is filling but columns have same values. What should i do?

function makeTeams() {

let teamsNum = document.getElementById("teamsNum").value;
    let playersNum = document.getElementById("playersNum").value;

if(playersNum %teamsNum == 0){
    const wrapper = document.querySelector(".wrapper");
    const tbl = document.createElement("table");
    const tblBody = document.createElement("tbody");
    let nums = []

    for(let x = 0; x < playersNum; x++){
        let random = Math.floor(Math.random() * playersNum + 1);
        if(nums.indexOf(random) === -1){
            nums.push(random);
            console.table(nums);
        } else x--;
    }

    for (let i = 0; i < playersNum/teamsNum; i++) {
      let row = document.createElement("tr");

      for (let j = 0; j < teamsNum; j++) {
        let cell = document.createElement("td");
        let cellText = document.createTextNode("Player " + nums[i]);
        cell.appendChild(cellText);
        row.appendChild(cell);
      }
      tblBody.appendChild(row);
    }

    tbl.appendChild(tblBody);
    wrapper.appendChild(tbl);
    tbl.setAttribute("border", "2");
    tbl.style.margin = "20px auto";
    tbl.style.width = "50%";
    tbl.style.textAlign = "center";

} else alert("Teams must have the same number of players!");

}




Array card count/ Histogram

I am currently making a program where one of the choices in where the user enters their rank ( highest card) and how many suits they have so hypothetically if one has a rank as 5 and 4 suits, they have twenty cards(1-5 cards). For one of the options the user has the decision to run the program 100,000 times and they are asked how many cards do they want dealt . Ex. User has a rank of 5 and 4 suits, the user wants to be dealt 3 cards, so the program out of 100,000 terms will calculate what they got for each result from 3 to 15( the possible sums you can get from picking cards 1 to 5 3 times). Its a histogram but without the visual aspect of it and it just shows the results, this is the whole program (https://github.com/alexxei4/cardcount). And specifically this is what im stuck on. All help and feedback is appreciated please and thank you

if(Choice ==3){
            System.out.println("How many cards would like to be drawn?");
            main.setcardask2(sc.nextInt());
            int[] maxcard = new int[(main.getcardask2() * main.getranks())+ 1];
            for (int i = 0; i < 100_000; i++) {
                int random = (int) (Math.random() * (highestthousand - lowestthousand + 1));
                maxcard[random]++;
            }
                for (int i = main.getcardask2(); i < 16; i++) {
                    System.out.println(i + ": " + maxcard[i]);

                }
         }




Python NRNG or how to implement it

I'm trying to find a very good Random Number Generator or to implement one in Python. I'm actually using numpy.random.normal() and for a size of N=100, the result is not so good for random variates i.i.d.

Do you have any suggestion?




Chrome infinite scroll - random delay / movement

I would like to be able to scroll to the bottom of a really long infinite scrolling page in Chrome using developer tools – but as several sites recognize this and block further scrolling, I would like to get as close to human behavior as possible.

Using the code below, would it be be possible to add a random delay and possibly opposite movement now and again? or any other ideas to avoid detection?

var lastScrollHeight = 0;
    function autoScroll() {
      var sh = document.documentElement.scrollHeight;
      if (sh != lastScrollHeight) {
        lastScrollHeight = sh;
        document.documentElement.scrollTop = sh;
      }
    }
    window.setInterval(autoScroll, 100);




Extract number with given probabilities in C

Let's say I have an array probabilities = [0.1, 0.2, ..., 0.1, 0.4] of n elements. These are floating point values, not weights.

How do I extract a random integer from 1 to n with the given probabilities in Ansi C?

probabilities = [0.1, 0.2, 0.1, 0.15, 0.05, 0.1, 0.4]
extract_random_integer(probabilities)




add numbers in different ways to a given sum in javascript

/I have the following issue; fixed sum substract of floats in numbers = rest. //console.log should give a new order of numbers/

var Nummer= [0.99, 1.99, 2.99, 3.99, 4.99, 5.99, 6.99, 7.99, 8.99, 9.99];
var summe= [30];


[30]

[0.99,
1.99,
0.99,
4.99,
6.99,
1.99,
2.99,
5.99,
4.99,
1.99,
0.99,]

[1.1]




mardi 18 juin 2019

How do I find the smallest value in an array of Complex numbers a + ci

import java.util.Scanner; import java.util.Random;

I'm trying to write a method which finds the smallest value in an array of Complex numbers a + ci, where a and c are both doubles. a is the real part and ci is the imaginary part. I'm trying to have it go through the array and compare each object a + ci and b + di. I was going to start by comparing the real parts and if the real parts were equal, then I would move on to the imaginary ones such that complexNumberOne < complexNumberTwo if a < b or if (a==b), c < d.

So far I have a method that can determine the smallest number in the array, but only by comparing the real parts:

private boolean arrayTest = false;

public double min(Complex[] arr) { double min = Double.MIN_VALUE;

        for(int i = 0; i < arr.length;i++) {
            if(arr[i].getReal() < min) {
                min = arr[i].getReal();
            }
        }
        return min;
    }

But my method to find the smallest element according the the aforementioned conditions seems to go nowhere:

public Complex smallest(Complex[] arr) {

        Complex min = new Complex();

        for(int i = 0; i < arr.length;i++) {
            while(!arrayTest) {
                if(arr[i].getReal()<arr[i+1].getReal())
                {
                    arrayTest=true;
                    min = arr[i];
                }else if(arr[i].getReal()==arr[i+1].getReal()) {
                    while(!arrayTest) {
                        if(arr[i].getImaginary()<arr[i+1].getImaginary()) {
                            arrayTest=true;
                            min = arr[i];
                        }
                    }
                }
            }
        }
        return min;
    }




Generate random latitude/longitude while avoiding oceans

I'm using https://randomuser.me/ to generate some random user data for testing. I'd like to geocode the latitude and longitude that provides to attach the real city/state/country information instead of the totally fake info that RandomUser provides. However, many of the actual lat/long values on these objects turn out to be in the middle of the ocean.

Is there an API, or some other method, that will let me get random coordinates which are always over land? I've seen this: Random geographic coordinates (on land, avoid ocean) But surely there must be some more efficient way than to just guess-and-check with constant geocoding until you find one that works, right?




Error with Random number generation in Swift on Linux?

I have a piece of code as follows:

extension Array {
  fileprivate func random() -> Element {
    let idx: Int
    #if os(Linux)
    idx = Int(random() % count)
    #else
    idx = Int(arc4random_uniform(UInt32(count)))
    #endif

    return self[idx - 1]
  }
}

When I attempt to deploy my app it errors when running docker using linux, the issue as follows:

error: binary operator '%' cannot be applied to operands of type 'Int32' and 'Int' idx = Int(rand() % count)

I tracked the issue down to this funciton but cant work out the fix here as it already is meant to provide an alternative handling for Linux...




How would I assign a random number between -99.99 and 99.99?

I need to assign a random number between -99.99 to be then stored into the real and imaginary parts of a complex number.




Generating a random uint64_t

Given a random number engine e of type E (of the type defined in <random>), how can I generate a some random uint64_t over their full range?

The engine e should remain useful after this (so for example move-constructing a std::independent_bits_engine doesn't seem like a good idea).




I want to know what's wrong in my code. A set of 2 die are rolled and random values are printed

I made a code for generating random values when a set of 2 die are rolled. Error says roll isn't defined. Can't figure out why it says that. I want to know what's wrong with my approach, I've already seen other solutions to the problem.

Novice programmer. My first problem related to generating random values.

import random
class Dice:
    def roll(self):
        roll = (1, 2, 3, 4, 5, 6)

toss = random.randint(roll)
print(toss, toss)
toss = random.randint(roll)

Error :

NameError: name 'roll' is not defined




How to use random generated values in methods?

I have tried to solve the following problem: I have 3 restaurants, each of them offers 4 items, with their respective prices. I should create a program to simulate the sales of each restaurant in a period of 3 months.

I should be able to run the following results: Random number of items sold by each restaurant every month (for example: first restaurant sold 5 of the first item in the first month, and so on). Based on those random values, show the total of sales (income) of each restaurant every month, and based on that, sort the restaurants from the biggest total of sales to the smallest one. And at last, total of items sold in all restaurants and their respective total income (for example: 100 of the first item were sold and the income of 100 of that item is... ).

As you surely may expect, I have already began the code, but I suspect I have made it wrongly, mainly because the values are manipulated wrongly (for example: the total income based on the sales of the items in a month does not correspond to their individual prices and quantities sold). I am going to show you the code, and I would I appreciate if you could help me with it.

My main questions are:

  1. Is my approach good? Could I solve the problem with it? 2. Why are the values of the outputs of each method different? 3. If there is a better approach, could you show it, please?

I created a class "Month", where there are the variables "restaurant, item1, item2, item3, item4". It has the constructor and a setter and getter method for the restaurant variable. I created four methods, each for I can generate a random number of each item. I also created four methods for I can calculate the total income of each item sold, based of the values of the methods to calculate the number of sold items, and then I created a method to calculate the total income of all items together, using the values of the former four methods. The problem is that as I said, it is creating independent results, as if the methods were not using the values of the other methods, and I did not find out how I could sort the restaurants based on their total incomes every month (even though I know how to implement sorting algorithms, but I could not do it in this case), besides I can calculate the total of each item sold in all restaurants in the period of three months, not their income.

import java.util.Random;

public class Month {
    private String restaurant;
    private double item1;
    private double item2;
    private double item3;

public Month (){
    this.restaurant=restaurant;
    this.item1=item1;
    this.item2=item2;
    this.item3=item3;
}

public double item1Sold (){
    Random item1Quantity = new Random();
    double item1 = item1Quantity.nextInt(30)+1;

    return item1;
}

public double item2Sold (){
    Random item2Quantity = new Random();
    double item2 = item1Quantity.nextInt(30)+1;

    return item2;
}

public double item3Sold (){
    Random item3Quantity = new Random();
    double item3 = item3Quantity.nextInt(30)+1;

    return item3;
}

public double totalIncome (){
    double income = item1Price()+item2Price()+item3Price();

    return income;
}

public double item1Price (){
    double price = item1sales()*50.00;

    return price;
}

public double item2Price (){
    double price = item2sales()*40.00;

    return price;
}

public double item3Price (){
    double price = item3sales()*30.00;

    return price;
}

public String getRestaurant() {
    return restaurant;
}

public void setRestaurant(String restaurant) {
    this.restaurant = restaurant;
}

/**In the main class, I have created only one month ("m1") as an array, 
and each value of the array would be a restaurant, but I am almost sure 
this approach is wrong **/

public class Main {

public static void main(String[] args) {
    Month [] m1 = new Month[2];

    m1 [0] = new Month();
    m1 [0].setRestaurant("rest1");

    m1 [1] = new Month();
    m1 [1].setRestaurant("rest2");

    for (int i=0; i<2; i++)
        System.out.println(m1[i].getRestaurant()+m1[i].item1Sales());

Sorry for the long message, but I had to give details. Thanks in advance.




lundi 17 juin 2019

Firefox not properly applying Pseudo Before and After classes in Firefox Windows only

In this Codepen : https://codepen.io/trevcis/pen/rgRePm

As you rollover a picture, a green expand box is shown that has a plus sign drawn with before/after pseudo classes on the 'close-toggle' div.

A seemingly similar problem at: https://stackoverflow.com/questions/21220360/firefox-not-displaying-properly-before-and-after-pseudo-elementshttps://stackoverflow.com/questions/21220360/firefox-not-displaying-properly-before-and-after-pseudo-elements

Seemed to fix the problem by applying inline-block/postiion:relative to it's parent, but it doesn't seems work.

It's 'weird' that Firefox on the Mac works just fine so would it be more of a bug in FireFox Windows? In fact it works on ALL other browsers that I tested it on.

This is code I inherited and was contemplating a rewrite but seems there's some approach that would fix it.

I tried applying the fix (set position/display on parent) that is in the somewhat related issue post:

.close-toggle, .PeopleBlock{
    position:relative;
    display:inline-block;
}

but it is the same result




the `_rand!()`function in julia

i have one quick question, what does _rand!() do in julia, i know it's about generating random numbers but what excatly does it do and is there any special function like it in python?

  • List item



Moving dots in different directions in a 3D space

I have this code that moves a number of dots all in the same direction in 2D space. I want to modify it in 2 steps:

  • I want each dot to move randomly in a different direction. This code makes them move all towards the same direction.

  • I want to create a 3rd dimension where the dots move randomly as well. I don't know how to compute dz (direction in z axis).

Any help would be appreciated. Thanks in advance!

dots.nDots = 100;                       % number of dots
dots.color = [255,255,255];             % color of the dots
dots.size = 10;                         % size of dots (pixels)
dots.center = [0,0];                    % center of the field of dots (x,y)
dots.apertureSize = [12,12];            % size of rectangular aperture [w,h] in degrees*


dots.x = (rand(1,dots.nDots))*dots.apertureSize(1) + dots.center(1);    
dots.y = (rand(1,dots.nDots))*dots.apertureSize(2) + dots.center(2);   

tmp = Screen('Resolution',0);                       
display.resolution = [tmp.width,tmp.height];

display.width = 30;                                
display.dist = 50;                                  

% This generates pixel positions, but they're centered at [0,0], which is the top left corner

pixpos.x = angle2pix(display,dots.x);               % Convert the x position of the dots from visual angle to pixel.
pixpos.y = angle2pix(display,dots.y);               % Convert the y position of the dots from visual angle to pixel.

%% We need to define some timing and motion parameters, which we'll append to the 'dots' structure:

dots.speed = 3;                 %degrees/second
dots.duration = 5;              %seconds
dots.direction_deg = 30;        %degrees (clockwise from straight up)
dots.direction_rad = dots.direction_deg * pi /180; % direction converted to radians


dx = dots.speed*cos(dots.direction_rad)/display.frameRate;
dy = -dots.speed*sin(dots.direction_rad)/display.frameRate;

nFrames = secs2frames(display,dots.duration);

%% Keeping the Dots in the Aperture
% We need to deal with dots moving beyond the edge of the aperture. This requrires a couple more lines of code.

%% First we'll calculate the left, right top and bottom of the aperture (in degrees)

l = dots.center(1)-dots.apertureSize(1)/2;
r = dots.center(1)+dots.apertureSize(1)/2;
b = dots.center(2)-dots.apertureSize(2)/2;
t = dots.center(2)+dots.apertureSize(2)/2;

%% New random starting positions
%%
dots.x = (rand(1,dots.nDots)-.5)*dots.apertureSize(1) + dots.center(1);
dots.y = (rand(1,dots.nDots)-.5)*dots.apertureSize(2) + dots.center(2);

%% Let's make the dots move in the aperture we have just specified
%%
try
    for i=1:nFrames
        %convert from degrees to screen pixels
        pixpos.x = angle2pix(display,dots.x)+ display.resolution(1)/2;
        pixpos.y = angle2pix(display,dots.y)+ display.resolution(2)/2;

        Screen('DrawDots',display.windowPtr,[pixpos.x;pixpos.y], dots.size, dots.color,[0,0],1);
        %update the dot position
        dots.x = dots.x + dx;
        dots.y = dots.y + dy;

        %move the dots that are outside the aperture back one aperture
        %width.
        dots.x(dots.x<l) = dots.x(dots.x<l) + dots.apertureSize(1);
        dots.x(dots.x>r) = dots.x(dots.x>r) - dots.apertureSize(1);
        dots.y(dots.y<b) = dots.y(dots.y<b) + dots.apertureSize(2);
        dots.y(dots.y>t) = dots.y(dots.y>t) - dots.apertureSize(2);

        Screen('Flip',display.windowPtr);
    end
catch ME
    Screen('CloseAll');
    rethrow(ME)
end
Screen('CloseAll');




Why Rmarkdown shows different random numbers in pdf output than the ones in the Rmd file?

I set.seed in Rmd file to generate random numbers, but when I knit the document I get different random numbers. Here is a screen shot for the Rmd and pdf documents side by side. Rmd and pdf side by side




random in MicroPython does appear to do anything?

Using pybricks-micropython

Running this command to get a random port number, works under CPython.

import random
port = random.randint(50000,50999)

produces a number, only it is hardly random it is the same number each time I run the script. I am guessing MicroPython needs something more perhaps?

What am I missing?




Random does not work in dotnetfiddle website?

Using random Next() function at the beginning of my program generates a new number every time while block executed. But Next() is outside the while cycle!

This question about website dotnetfiddle.net and random generator. The very simple and obvious program does not work.

// Guess number game

    // NOTE! Works perfect if I use a constant number instead of Random.  
    Random rnd = new Random();
    int number = rnd.Next(1, 100);
    int userInput = 0;
    bool isPlaying = true; 

    while (isPlaying) {
        try {
            userInput = Int32.Parse(Console.ReadLine());
        }
        catch (FormatException e)
        {
            Console.WriteLine(e.Message);               
        }

        if (userInput < number) {
            Console.WriteLine("more");
        } else if (userInput > number) {
            Console.WriteLine("less");
        } else {
            isPlaying = false;
        }
    }

    Console.WriteLine("You win");

https://dotnetfiddle.net/uy3Phc

How to solve this?

I was not able to find any support contacts so I put question here.




Generate samples from data following normal distribution but with new mean

I have a vector of numbers that is

set.seed(1)
x <- rnorm(8334, 1.456977, 0.3552899)
mean(x)
[1] 1.454307

Essentially, I want to randomly sample 2000 numbers from x such that mean of this sample is lower.

The key is I don't want to generate new random numbers but only sample from x, without replacement, such that I get a subset with a different mean.

Can anyone help me?

Thanks!




Match 2 people together from list randomly using one condition

I am creating an excel sheet to randomly match 2 employees together from a list. Only criteria is that the employees cannot be apart of the same department.

I've created a formula that randomly matches people from a list, but have not been able to only match people if they are in different departments.

=INDEX($A:$A,RANDBETWEEN(1,COUNTA($A:$A)),1)

I expect the output to be: "John Doe IT" "Noah Body HR"

the current function can output: "John Doe IT" "Jane Doe IT"




random.randint not working within given range

I have homework in python. I need to write a program that guesses a number which the user select in the range of 0-100.

I tried to write the program with random, the program prints the random int and receives input if its to high or to low. if its to low, the program generates a number between the number it printed and 100(or if it a higher number than that is the max the code can generate) but for some reason when I enter that the number it printed is to high, it doesn't set the higher number to the maximum range.

import random
high = 100
low = 0
tries = 0
print("select a number between 0-100")
x = random.randint(low, high)
print("is it: " +str(x) +"?")
while True:
    y = input("enter high if guess is higher, enter low if guess is lower and enter correct if guess is correct\n")
    if y == "low":
        low = x
        x = random.randint(low, high)
        print("is it: " +str(x) +"?")
        tries +=1
        continue
    elif y == "high":
        hige = x
        x = random.randint(low, high)
        print("is it: " +str(x) +"?")
        tries += 1
        continue
    elif y == "correct":
        print("it took: " +str(tries) +" tries")
        c = input("enter c to close and co to continue")
        if c == "c":
            break
        elif c =="co":
            continue
    else:
        print("enter valid input:\n")
        continue

I want the maximum range would be the highest number the code generated last. thank you for helping :)




Randomize a #define at program start

I have an application which has a strict separation between user and the backend. The only way the user can interact with my backend is via one function. To specify what the user wants the first argument of this fucntion is the instruction the user wants the backend to execute (for example getData). This looks something like this

backendcall(getData, arg1, arg2, arg3, arg4)

The names of the services that my backend provides are saved in a .h file (called definitions.h). This file only contains #defines.

#define getData 1
#define setData 2
...

This way the user it is easier for the user. For security reasons I would like to randomize the value of the #defines at the start.

I am aware that it is possible to call functions in a define like this #define var foo()

My problem is that this does not work for me since I can not use a function to define the random value. Even if I add an integer like this

int asdfqweryxcv = 20;

I get an error message on compilation that this value has multiple definitions. I can change the name to whatever I want the result is always the same.

The Error message looks like this:

../../lib.a(userfile1.c.o):/home/../../../definitions.h:8: multiple definition ofasdfqweryxcv' CMakeFiles/mult.c.o:/home/../../../definitions.h:8: first defined here

../../lib.a(userfile2.c.o):/home/../../../definitions.h:8: multiple definition of `asdfqweryxcv' CMakeFiles/mult.c.o:/home/../../../definitions.h:8: first defined here

... ...`

I would like to randomize these defines and have a unique number for every define.




C++ Three dimensional array random access performance

I would like to boost the performance of application which stores 3D map. Currently, it uses QtreeNode as a structure for storing the map. However, accessing random position with coordinates x,y,z has a complexity of log2n.

I would like to store part of the map which I know is accessed 90% of the time in the static array defined as:

Tile* tileArray[16][3500][3500] // [z, x, y];

The reason I set z as first dimension is that application iterations are usually done floor by floor and row by row.

Tile* is a pointer to a data structure containing information about that position on 3D map. Since the system is 64bit and the pointer size is 8byte and it takes a total of 1.5GB of RAM.

I would like to ask if there is some problem with random accessing such an array with x,y,z coordinates. Logically, the complexity should be O(1) but I am not sure about how CPU calculates the exact position in the memory.

I am not afraid of excessive RAM usage.




Is there any way to pick weighted random values along with random number of pick value?

I have below kind of data with me

keys = [a] , [b] , [a,c] , [b,c,a]

frequencies = [1] , [2] , [2,2] , [1,1,2]

count = 1, 1, 2, 3

def get_item(items, items_weights):
    return random.choices(items, weights=items_weights)

above function just provides me single random key from my data I want multiple keys based on distribution of count

I want to pick keys based on their frequencies as well as count so that I can get random keys with random count




dimanche 16 juin 2019

Can MacBook run the CUDA library..?

I have been using a Mac pro 2011 model, on which running a deep learning models is such a impossible task due to its limited resources.

So my question is that recently I started learning deep learning and I need a powerful laptop on which I can run the deep learning models locally, so please suggest which should I buy. My preference would be to buy a MacBook pro but I got to know that many deep learning libraries uses CUDA as a background which in turn uses a Nvidia gpu but Mac doesn't have that, so can a Mac run the CUDA library even if it doesn't have a Nvidia gpu




how to set up a random sequence to perform certain groups of lines in python?

the question is about python. What I have got is a list. In this list, I got questions, each question requires users to input, for example: enter image description here I want the students to give correct answer to the questions, so each question contains a while loops. I want the questions to be performed in random sequence, after they have answered each question once, finish the code.

I have read about the random sequence, however, all of them are about statistics. could you please offer me some help? thanks a lot.

PS print("sorry, I need to use the picture to show the codings") PPS print("when I use the code code tools {} in the tool bar, I can't insert codes such as s_t_r, anyone knows why?")




When trying to run a script to test whether tensorflow is installed I get a massive error that I do not understand

I have a script to try and test tensorflow's installation as seen here:

import tensorflow 

And get a massive error that also includes an error to do with random in it.

  File "tensorflowtest.py", line 1, in <module>
    import tensorflow
  File "C:\Users\jiney\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\jiney\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\__init__.py", line 47, in <module>
    import numpy as np
  File "C:\Users\jiney\AppData\Local\Programs\Python\Python36-32\lib\site-packages\numpy\__init__.py", line 187, in <module>
    from .testing import Tester
  File "C:\Users\jiney\AppData\Local\Programs\Python\Python36-32\lib\site-packages\numpy\testing\__init__.py", line 12, in <module>
    from ._private.utils import *
  File "C:\Users\jiney\AppData\Local\Programs\Python\Python36-32\lib\site-packages\numpy\testing\_private\utils.py", line 16, in <module>
    from tempfile import mkdtemp, mkstemp
  File "C:\Users\jiney\AppData\Local\Programs\Python\Python36-32\lib\tempfile.py", line 45, in <module>
    from random import Random as _Random
  File "C:\Users\jiney\Desktop\random.py", line 2, in <module>
    print (random.randint(16, 17))
AttributeError: module 'random' has no attribute 'randint'

I genuinely have no idea what any of this means, or how to fix it, or what it means.




Get a random number within a range with a bias

Hello i am trying to make a method to generate a random number within a range where it can take a Bias that will make the number more likely to be higher/lower depending on the bias.

To do this currently i was using this

 public int randIntWeightedLow(int max, int min, int rolls){

    int rValue = 100;

    for (int i = 0; i < rolls ; i++) {
        int rand = randInt(min, max);

        if (rand < rValue ){
            rValue = rand;
        }
    }

    return rValue;
}

This works okay by giving me a number in the range and the more rolls i add the likely the number will be low. However the problem i am running in to is that the there is a big difference between having 3 rolls and 4 rolls.

I am loking to have somthing like public void randomIntWithBias(int min, int max, float bias){ }

Where giving a negative bias would make the number be low more often and a positive bias make the number be higher more often but still keeping the number in the random of the min and max.

Currently to generate a random number i am using

 public int randInt(final int n1, final int n2) {
    if (n1 == n2) {
        return n1;
    }

    final int min = n1 > n2 ? n2 : n1;
    final int max = n1 > n2 ? n1 : n2;

    return rand.nextInt(max - min + 1) + min;
}

I am new to java and coding in general so any help would be greatly appreciated.




Why does the variable d1 in a function give the error "d1 is not defined" (it was working but now it's not)

'''This is the version of a dice-roll I came up with. I know I am not that smart, and rather slow minded. But I am trying learn and make this code work. The variable d1 is getting the error "d1 is not defined", which stops the roll.'''

import numpy as np
import pandas as pd
import random
from statistics import mean, stdev

def dice():
    count = 0
    d1=([random.randint(1,6) for _ in range(10)])
    count = count + d1  
    d2=([random.randint(1,6) for _ in range(10)])
    count = count + d2

    tot=(d1+d2)
    medi=mean(d1,d2)
    stand=stdev(d1,d2)

print(d1,d2) print(tot) print(medi) print(stand)




Random number like java in c++

I have a need to generate a random number 0 or 1 to simulate the coin toss. It is easily possible in Java whereas in C++ I am having difficulty. I searched in a lot but didn't find a satisfactory answer. There are many random related questions in stackoverflow, but none of them answer this. If you can help, it will be really appreciable.

Here is my code

for (size_t i = 0; i < 50; i++)
    {
        srand(time(0));
        int k = rand() % 2;
        cout << k;
    }

The output is all 0 or 1. It is because the seed for srand is same time.

Is there any solution for this?