mardi 23 janvier 2024

Quantiles of sums of independent discrete random variables

I have the following problem: given k (=10) discrete independent random variables X_i with n_i ( = 5 to 20) values each.

Problem: compute quantiles of the distribution of the sum X = X_1+...+X_k.

Here X has n=n_1 x n_2 ... n_k distinct values which is too large to list them all together with their probabilities.

I tried several approaches:

(A) Convolution:

each X_j is approximated with Y_j=X_j+Z, where Z is a normal N(0,sigma) variable with small sigma. Then Y_j is a probability mixture of the normal variables N(x_j,sigma), where the x_j runs over all values of X_j, and has a highly oscillatory density.

The density of Y=\sum Y_j is the convolution of the densities of the Y_j.

I need this density at a sizeable number of points and this turns out to be too slow. The issue seems to be the convergence of the convolution integrals slowed down by the oscillatory nature of the densities of the Y_j. When the densities are behaved better (e.g. normal RVs), the computation of such a convolution is quite fast.

(B) Characteristic function:

X will be approximated with Y=X+Z, where Z is normal N(0,\sigma) with small sigma. Y has a density (which it is impossible to compute directly) but the characteristic function (continuous Fourier transform) cf_Y of Y can easily be computed analytically (without knowing the density of Y)

Now let s be a numeric vector. I want to get the density f_Y(s) of Y evaluated along s. The proper way of doing this would be to apply the inverse continuous Fourier transform to the function cf_Y at each point in s.

This is far too slow. That's why I tried to apply the inverse discrete Fourier transform to the vector of values cf_Y(s) and that does not yield anything reasonable.

This baffles me since I was under the impression that the discrete Fourier transform is an approximation to the continuous Fourier transform and so should yield the values of the latter, if the value grid s is fine enough.

Should this work?

Note that this inversion would definitely work if I could compute the discrete Fourier transform of the density f_Y along s, but regrettably this is not possible since

(a) the density of f_Y is far too complicated, and

(b) the discrete Fourier transform of a sum Y = Y_1+Y_2+...+Y_k of independent random variables Y_j is not the product of the discrete Fourier transforms of the Y_j.

Any ideas how I could approach this problem with the tools of R?




mercredi 17 janvier 2024

Random Choice in If statement [closed]

I am a beginner and im wondering how to code something like this in python:

If this word from a list of given words is randomly picked print ("")

I am trying to code a little game but i cant code any further without this piece of code.




samedi 13 janvier 2024

Simple Scaling Probability With Outliers in Python

I'm creating a virtual auction game, and I need more complex NPC behavior than I have now. Basically, every item has a base price (bp), and the starting bid (sb) for that item will be calculated with this range (or something very similar): 0.8bp <= sb <= 1.1bp. The opposing NPC bidders need to judge how reasonable the current bid is, compared to the base price and/or starting value, and, with some outlying behavior (i.e. betting when it seems a little irrational), bid reasonably on the current item. Put simply, it should bid aggressively on the item when the bid is lower or around the base price, and frugally bid on the item if it's high above the base price, or just give up.

The issue is, I really have no idea how to do this. Not only that, this is going to mainly be run on a TI-84 Plus CE calculator, so the external libraries and modules have to be pretty limited (essentially just random). It'd be great if you attach a brief (or long) explanation of any formulas/code you provide, because I'd love to learn more about this.




What is the modulus of the libc pRNG LCG?

I'm a bit confused at the moment about the linear congruential generator used in the rand() function in stdlib to generate random numbers. The table on https://en.wikipedia.org/wiki/Linear_congruential_generator lists the modulus used by GCC and for ANSI C as 2^31. However, according to https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf p347, for ANSI C 2^32 is implicitly used. Does rand() in stdlib also use 2^32?

I've implemented and tested the ANSI C implementation, which works fine.




reduce a list of objects given an associated list of likelyhoods

I have a list (aka, slice) of objects. I also have a list of the same size that contains the likelyhood that each object will be useful in the future. I need to reduce my object list length so that it has n or fewer elements. (It may or may not have n+ elements to start.) How can I do this efficiently?

I was thinking I could sort the object list according to the probabilities and then truncate it. However, I want the low-probability objects to have a chance of remaining. I was also thinking that I could check the probability on each item against a random number to see if it lives or dies, but then I might end up with fewer than n items in the end.




vendredi 12 janvier 2024

Why are all the strings the same

For test my hashmap on C language I need to generate many keys (string). I wrote this code for generate keys. And this code doesn't works.

    char* keys [15] = { 0 };

    for (int i = 0; i < 15; i++)
    {
        char key [7] = { 0 };
        for(int j = 0; j < 5; ++j)
        {
            int rand_char = rand()%26+'A';
            key[j] = (char)rand_char;
        }
        *(keys + i) = key; 
    }

    for (int i = 0; i < 15; i++)
        printf("%s\n", keys[i]); 

The problem is all keys are the same and I don't know why this happens. OUPUT:

MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ

I tried putting the random result into a variable (int rand_char) and also tried the debug keys during the generation process and saw that all the letters change when new letters are generated, as if all the lines were one string.

char* keys [15] = { 0 };

for (int i = 0; i < 15; i++)
{
    char key [7] = { 0 };
    for(int j = 0; j < 5; ++j)
    {
        int rand_char = rand()%26+'A';
        key[j] = (char)rand_char;
        for (int k = 0; k < i; k++)
            printf("%s\n", keys[k]); 
    }
    *(keys + i) = key; 
}

OUPUT:

B
BM
BMQ
BMQB
BMQBH
C
C
CD
CD
CDA
CDA
CDAR
CDAR
CDARZ
CDARZ
O
O
O
OW
OW
OW
OWK
OWK
OWK
OWKK
OWKK
OWKK
OWKKY
OWKKY
OWKKY
H
H
H
H
HI
HI
HI
HI
HID
HID
HID
HID
HIDD
HIDD
HIDD
HIDD
HIDDQ
HIDDQ
HIDDQ
HIDDQ
S
S
S
S
S
SC
SC
SC
SC
SC
SCD
SCD
SCD
SCD
SCD
SCDX
SCDX
SCDX
SCDX
SCDX
SCDXR
SCDXR
SCDXR
SCDXR
SCDXR
J
J
J
J
J
J
JM
JM
JM
JM
JM
JM
JMO
JMO
JMO
JMO
JMO
JMO
JMOW
JMOW
JMOW
JMOW
JMOW
JMOW
JMOWF
JMOWF
JMOWF
JMOWF
JMOWF
JMOWF
R
R
R
R
R
R
R
RX
RX
RX
RX
RX
RX
RX
RXS
RXS
RXS
RXS
RXS
RXS
RXS
RXSJ
RXSJ
RXSJ
RXSJ
RXSJ
RXSJ
RXSJ
RXSJY
RXSJY
RXSJY
RXSJY
RXSJY
RXSJY
RXSJY
B
B
B
B
B
B
B
B
BL
BL
BL
BL
BL
BL
BL
BL
BLD
BLD
BLD
BLD
BLD
BLD
BLD
BLD
BLDB
BLDB
BLDB
BLDB
BLDB
BLDB
BLDB
BLDB
BLDBE
BLDBE
BLDBE
BLDBE
BLDBE
BLDBE
BLDBE
BLDBE
F
F
F
F
F
F
F
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ELLN
RELLN
RELLN
M
M
M
M
M
M
M
M
M
M
M
M
M
M
MP
MP
MP
MP
MP
MP
MP
MP
MP
MP
MP
MP
MP
MP
MPA
MPA
MPA
MPA
MPA
MPA
MPA
MPA
MPA
MPA
MPA
MPA
MPA
MPA
MPAP
MPAP
MPAP
MPAP
MPAP
MPAP
MPAP
MPAP
MPAP
MPAP
MPAP
MPAP
MPAP
MPAP
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ
MPAPQ



jeudi 11 janvier 2024

How do I get a random choice from a list to not give me duplicates?

Sorry if it's unclear, beginner here. Basically I have this to pick random questions for a quiz:

import random

econ = ["eq1", "eq2", "eq3", "eq4", "eq5", "eq6", "eq7", "eq8"]
mil = ["mq1", "mq2", "mq3", "mq4", "mq5", "mq6", "mq7", "mq8"]
oro = ["oq1", "oq2", "oq3", "oq4", "oq5", "oq6", "oq7", "oq8"]
pol = ["pq1", "pq2", "pq3", "pq4", "pq5", "pq6", "pq7", "pq8"]

cats = [econ,mil, oro, pol]
 
for x in cats:
        for y in range(3):
            print(random.choice(x))

However, I sometimes get duplicates, example: eq3 <- here eq3 <- here eq1 mq5 mq7 mq2 oq1 oq4 oq5 pq3 pq7 pq2

I've scoured through forums and the python coding book but was unable to find something that didn't confuse me more!

TL;DR: How do I avoid repetition of random items in the code?




mercredi 10 janvier 2024

Int won't print in the txt file [closed]

I am trying to print a random generated serial along with a name and a date in a txt file. The name and the date prints and get saved but only a question mark appears in the place of the supposed serial digits.

I tried changing the int to long but it does nothing, so does the suggestion.




vendredi 5 janvier 2024

Random.Next() generates same value forever. in Paralled.Foreachasync [duplicate]

I create a Random object at the start of my method. Then in that method I run a Parallel.Foreachasync loop.

Inside this I generate 2 random numbers using Random.Next(). I then check to see if the numbers are the different in a while loop. In the while loop I generate a new random number until they are different. For the first few thousand loops this works fine. Then suddenly it gets stuck generating the same number over and over again...

var room1Index = rnd.Next(0, slot1.RoomList.Count - 1);
var room2Index = rnd.Next(0, slot2.RoomList.Count - 1);

while (room1Index == room2Index)
{
    room2Index = rnd.Next(0, slot2.RoomList.Count - 1);
}

I have checked the roomlist count and it is 4 so I would expect the two numbers to be different at least after a few iterations... However it always generates 0

Why could this be happening?




jeudi 4 janvier 2024

Generating a random sequence of numbers in Python using a dash [closed]

It is necessary to make a random sequence of numbers in Python through a dash, for example, 46417635-7485-8418-8754-651578178453.

Using the random module and the randint function, it was possible to generate numbers in a certain interval (str(random.randint(100, 150). How to make a sequence of numbers separated by a hyphen?




How to give equally probable chances for random loot box opening? [duplicate]

Let's say I am working on a game in C# and want to give the player ability to open a loot box. Let's say we have 5 tiers of rarity for all items in the game. Common - 60%, Uncommon- 20%, Epic - 7.5%, Special - 7.5% Legendary - 5%

Most code I see online says to generate a random number between 1 and 100 for example, and then compare that random number to each rarity until you get a hit.

However, how could this be possible of "Epic" and "Special" both have the same probability? Let's say the random number is 6. How do I know if I should give them a special or an Epic? What I really want is there to be a 7.5% chance that epic and also a 7.5% chance that 'special' can be obtained. How do I do that?




mercredi 3 janvier 2024

Given a RNG in python, Estimate Pi [closed]

I recently watched a popular youtube video that posed the question:

Given a random number in [0,1], write a python program that estimates pi

Before the video gave their solution I came up with the following:

import random 
import math

a=0

n = int(input("Please specificy a number: \n"))

for i in range(n):
    x_i = random.random()
    y_i = random.random()
    d_i = math.sqrt((x_i)**2 + (y_i)**2)
    if d_i <= 1:
        a=a+1


print(4*(a/n))

I watched the rest of the video and my answer was logically equivalent with just some minor differences in syntax. My background is in mathematics so I was able to come up with the mathematical solution that yielded some pseudocode, but I am a very novice programmer so then I googled my way through turning the pseudocode into functional python code. My question for you! experienced users and programmers is: can you tell me a logically equivalent solution to mine that would be preferred if you saw it at work?

Now, I know that is a subjective question that could depend on situation, style, and preference, so let me try to make this question more fit for the community:

Please re-write the above program and point out why yours has superior:

  • elegance
  • readability
  • speed
  • utilization of improvements in python language
  • robustness



dimanche 31 décembre 2023

How does Javascript convert the result of xorshift128+ to a float value between 0 and 1 for Math.random()?

I need to write a program exploiting cryptographic insecurity of javascript's Math.random() for a CTF thing. However I do not know how javascript converts an int to a float between 0 and 1. The pseudo-randomization algorithm of javascript, as far as I understand is xorshift128+, which in python would look something like this:

def cast_to_int32(x):
    return x & 0xffffffff


def xorshift128plus():
    global state0
    global state1
    state0 = cast_to_int32(cast_to_int32(18030 * (state0 & 0xffff)) + cast_to_int32(state0 >> 16))
    state1 = cast_to_int32(cast_to_int32(30903 * (state1 & 0xffff)) + cast_to_int32(state1 >> 16))
    return cast_to_int32(cast_to_int32(state0 << 16) + (state1 & 0xffff))

However bitwise operations in this scenario are performed on integers, not floats. But the result of javascript's Math.random() is a float between 0 and 1. How does javascript convert that? I know the most intuitive thing to suggest would be a simple division by 2^32 or 2^31 but I've tried that and couldn't reproduce the results.

I tried dividing the int result by (2^31-1),(2^31),(2^32-1),(2^32) but none of these reproduced the results of Math.random() from the same state.




samedi 30 décembre 2023

How can i pass a random number generator as argument to a function that will produce several different numbers inside the function? [duplicate]

So, I have created several different random number generator functions (rng) that produce values of a random variable X which follow different distribution functions. Now, I want to experiment with the central limit theorem, and have a function (x_n) that produces n different values of X for a given distribution function, so, given the distribution function, I want to produce several different values of X, and then find their mean value.

I tried to just define a function that takes as arguments the number of values I want to generate and the function f (the rng) that I want the variable X to follow. I tried to call the RNG inside the function several times, but, of course, when I put the predefined distribution function as an argument into the x_n(n,rng), it generates only one random number, into the argument section, and then this random number is used throughout the entire run of x_n.

How can I call the rng many times inside the function x_n(n,rng) and produce many different numbers inside of it?

import random as r

#def uniform():
    #return r.random()

def x2():
    u=r.random()
    return u**(1/3)

def x_n(n,f):
    x_n=0
    for i in range(n):
        rand=f
        x_n+=rand
        #print(rand)
    return x_n/n

x_n(5,x2())
x_n(7,r.random())
x_n(20,uniform())

P.S.: One idea I had was to create random number generators that take an argument and just change the argument inside x_n()'s loop, but I was hoping there was another way, so that I can pass just r.random() as the distribution function.




lundi 18 décembre 2023

Restricted C Struct Randomizer

I am attempting to randomize members of a C struct with a few difficulties:

  1. The randomized struct may not be larger than the original one
  2. Each member has an alignment which has to be respected
  3. Members are of different sizes obviously
  4. Some members are fixed in place
  5. Members may not overlap with respect to their sizes
  6. Each member has a range in which it has to end up [min offset, max offset]

I freestyled a randomizer that respects properties 1 to 5. Also taking into account property 6 greatly complicates things. Is there an algorithm that does this kind of thing or could be abused to do it?

For context:

I have this struct representing the properties of a member of a C struct:

struct Member {
    uint32_t size;
    uint32_t offset;
    uint32_t alignment;
    uint32_t maxadd; // Max increase of offset
    uint32_t maxsub; // Max decrease of offset
};

My randomizer gets a list of objects of this struct, one object per member. It is supposed to find new, randomized offsets for each member, while not having any members overlap in the end and not translating a member by more than maxadd/maxsub.

I am not trying to randomize the strings in a struct definition. I am trying to randomize the memory layout itself. Because it is supposed to work on fully compiled binaries, the resulting layout may not consume more memory than the original struct (e.g. by translating a member by a million bytes). My randomizer also knows the size of the original struct.




Distributing random numbers with multiple conditions

My students handed in group projects. Now they are supposed to give feedback to other student's works. Each student should give feedback to two other student projects. I want to assign these projects randomly. Two conditions have to be met:

  1. A student should not give feedback to their own project.
  2. A student should not give feedback to the same project twice.
#Example Data
group <- c(1,1,1,2,2,3,3,3,4,4)
name <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j")
feedback1 <- c(1,1,1,2,2,3,3,3,4,4)
feedback2 <- c(1,1,1,2,2,3,3,3,4,4)
df <- data.frame(group, name, feedback1, feedback2)

As you can see, the groups are not the same size (some groups have 2 members, some have 3). I created a loop that checks if someone is about to give feedback to himself. If so, a random number is chosen from all the group numbers, until a fitting number is chosen. One occurrence of the chosen number is then removed from the group numbers and the next student is checked.

# Fill feedback1
for (i in 1:nrow(df)) {
  while (df$feedback1[i] == df$group[i]) {
    df$feedback1[i] <- sample(group, 1)
  }
  group <- group[-match(df$feedback1[i], group)]
}

This works so far:


   group name feedback1 feedback2
1      1    a         2         1
2      1    b         3         1
3      1    c         3         1
4      2    d         1         2
5      2    e         1         2
6      3    f         4         3
7      3    g         4         3
8      3    h         2         3
9      4    i         1         4
10     4    j         3         4

If I add the second condition ("students should not give feedback to the same groups") the loop fails to work:

# Fill feedback2
group <- c(1,1,1,2,2,3,3,3,4,4)

for (i in 1:nrow(df)) {
  while (df$feedback2[i] == df$group[i] & df$feedback1[i] == df$feedback2[i] ) {
    df$feedback2[i] <- sample(group, 1)
  }
  group <- group[-match(df$feedback2[i], group)]
}

I do not get an error message, but df$feedback2 just stays the same for all students:

 group name feedback1 feedback2
1      1    a         2         1
2      1    b         3         1
3      1    c         3         1
4      2    d         1         2
5      2    e         1         2
6      3    f         4         3
7      3    g         4         3
8      3    h         2         3
9      4    i         1         4
10     4    j         3         4
  1. What is the mistake in my second loop for feedback2?
  2. What would be (in general) a better way to do approach the problem?

Best regards




Issue of random background in firefox browser

I've got script of random background which is working of every browser except firefox (only mobile version). In this browser the images not covering all screen but some part.

Here is a code:

<script>function pic() {

var bgm = ['image1.webp', 'image2.webp'];

$('body').css({ 'background': 'url(' + bgm[Math.floor(Math.random() * bgm.length)] + ') no-repeat', 'background-attachment': 'fixed', 'background-position': '50% 50%', 'background-size': 'cover' }); }

pic();

Why on firefox browser (only mobile version) the image not cover all screen?




dimanche 17 décembre 2023

How to predict Random numbers

If I have some code like this:

import random
for i in range(10):
    print(randint(0,1))

Now I know the previous 10 outputs how can I predict the 11th one? I know it's possible, how can I find it?




lundi 11 décembre 2023

Excel VBA Code for lottery and duplicates

I want to make a lottery in Excel where I can draw aprox 30 random numbers between 1-1000 and where the 30 numbers aren't duplicates.

I can't figure out how to check if the Array have duplicates and run the code again if so.

I currently use below VBA code to generate random numbers/winners. I do not think this is the most efficient way but this is what i got... :)

Public Sub CommandButton1_Click()
    Dim MIN, MAX, OUT, i
    Static a, n, z
    MIN = Array(1, 1, 1, 1): MAX = Array(10, 10, 10, 10): OUT = Array("Q1", "Q2", "Q3", "Q4")
    z = UBound(MIN)
    If Not IsArray(n) Then ReDim a(z): ReDim n(z)
    For i = 0 To z
        If n(i) = 0 Then Reset a(i), n(i), MIN(i), MAX(i)
        Range(OUT(i)) = a(i)(n(i)): n(i) = n(i) - 1
    Next
End Sub

Private Sub Reset(a, n, MIN, MAX)
    Dim i, j
    Randomize: n = MAX - MIN + 1: ReDim a(1 To n)
    For i = 1 To n
        j = Rnd * (i - 1) + 1: a(i) = a(j): a(j) = i - 1 + MIN
    Next
End Sub

If you can help me or know of a better way to code this please hmu! :)

Thanks! Oskar




mercredi 6 décembre 2023

Difficulty generating unique random numbers using Python's random module [closed]

I am working on a project where I need to generate a list of unique random numbers in Python using the random module. I've tried using random.sample to achieve this, but I'm running into issues with [describe the specific problem or error].

Here's a simplified version of my code:

import random

# Some code here to initialize a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Attempt to generate a random subset of unique numbers
try:
    random_subset = random.sample(numbers, k=5)
    print(random_subset)
except ValueError as e:
    print(f"Error: {e}")

Can someone please guide me on how to properly generate a subset of unique random numbers using the random module in Python?