ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sun, 31 May 2020 22:15:21 +0200Pb with an integer random drawhttps://ask.sagemath.org/question/51661/pb-with-an-integer-random-draw/The following code do nearly what I expect : defining random numbers whose sum equal a given number. Unfortunately, if i change `RR` for `ZZ` it return an error --- and of course I need integers.
elec=100
candidats= 4
nn=list([i for i in range(candidats-1)])
PP=([0 for i in nn])
PP[0]=RR.random_element(0,elec)
for k in nn:
PP[k]=RR.random_element(0,elec-sum(PP[j]for j in nn[:k]))
show(PP)
show(sum(PP))
I do not understand my error since it was working at the beginning. Also the sum was nearly always equal to elec with some time a unit of difference. Also is there a command to shuffle the number inside the list.CyrilleSun, 31 May 2020 22:15:21 +0200https://ask.sagemath.org/question/51661/Generate a random non-singular matrix?https://ask.sagemath.org/question/45579/generate-a-random-non-singular-matrix/I do this in a loop now:
while:
A = random_matrix(...)
if(not A.is_singular()):
....
But this is innefficient. How do I generate random matrices with more concrete properties in sage?rijndaelxyzFri, 01 Mar 2019 06:44:45 +0100https://ask.sagemath.org/question/45579/2d Random march Markov'Chainhttps://ask.sagemath.org/question/45425/2d-random-march-markovchain/Hi
problem of the robot that moves symmetrically with steps of 1 on a graduated network (table),
starting from the origin can be interpreted as the problem of the ruin of the "two-dimensional" player,
I put the sageMath code to solve this problem on cocalc.com in order to share it. Maybe it can help SageMath beginners get started.
However, I do not think my code is optimal ! Any constructive criticism will be welcome.
[code on cocalc.com](https://cocalc.com/share/bed80555-322d-4f9a-a456-e2473a51ff95/muGamblerRuin.ipynb?viewer=share)
[a discussion on the subject](https://www.maths-forum.com/informatique/gambler-ruin-markov-chain-t204039.html)ortolljTue, 12 Feb 2019 09:08:12 +0100https://ask.sagemath.org/question/45425/Uniform random choice of integerhttps://ask.sagemath.org/question/40960/uniform-random-choice-of-integer/I want to perform some statistical sampling and to do this I need to uniformly randomly choose an integer from [0, N) where $N \approx 10^{50}$. It appears that there are several plausible ways to do this in Sage:
1) randint(0, N-1)
However, the standard Python random library appears to have some non-uniformity, for example [see this ticket](https://bugs.python.org/issue9025).
2) import numpy; numpy.random.randint(0, N)
However, since N is so large, this raises
ValueError: high is out of bounds for int64
3) ZZ.random_element(0, N)
> Do either of the issues that methods 1) and 2) suffer from apply to method 3)? That is, is 3) the correct way to integers uniformly at random?Mark BellSat, 03 Feb 2018 19:28:10 +0100https://ask.sagemath.org/question/40960/remember and collect values/outputhttps://ask.sagemath.org/question/39749/remember-and-collect-valuesoutput/Hello, I am working with a function that involves random values. Thus, every time I run my code I get different values(in my case it is a set of values). When I get my output I want Sage to remember it and collect it every time I run my code. At the end I'd like to get a list of sets that has been accumulated every time I ran my code. Is there a way to do it?
I tried to research this topic and haven't found anything except saving a list to .txt file.XeniaThu, 23 Nov 2017 21:07:44 +0100https://ask.sagemath.org/question/39749/Rounding entries of a random vectorhttps://ask.sagemath.org/question/39697/rounding-entries-of-a-random-vector/Hello,
I am trying to generate a random diagonal matrix, defined by a random vector over a field RR. The problem is that I need to round all the values to two decimal places, make entries evenly positive and negative (not necessary of equal amount) and, ideally, avoid zeroes.
I have a code
`[round(4*random()-2,2)for i in[1 .. 8]]`
that produces a list of values that I need of size 8. However, I am struggling to combine it with a command `diagonal_matrix` and insert it there.
Also, I don't really understand why do we need to multiply it by 4 in here
`[round(4*random()-2,2)for i in[1 .. 8]]`
and why it produces negative values only, if I multiply it by 2 instead of 4. Could someone explain it please?
Is there any other simpler and more elegant way to solve this problem? Thank you.XeniaTue, 21 Nov 2017 14:53:11 +0100https://ask.sagemath.org/question/39697/How to generate graphs random geometric shapes?https://ask.sagemath.org/question/38484/how-to-generate-graphs-random-geometric-shapes/ I would like to create practice problems, rather than reusing old exam questions, to help my students practice solving geometric problems. I would like to use sagetex to produce random variations similar the questions I have listed below. I would supply examples of the pictures, but I do not have enough points to post pictures.
I am wish to be able to make one worksheet where each time it is printed, the values would be randomly assigned and graph would be produced. I know how to assign a random integer value to a variable; however, how to produce the graphs I have no understanding of how to achieve that. Thus for each of the example problems how to make the graph and how to assign the random variability to that graph.
**Example questions**
*The diagram below shows a child’s toy which is made up of a circular hoop, centre O, radius 7 cm. The hoop is suspended in a horizontal plane by three equal strings XA, XB, and XC. Each string is of length 25 cm. The points A, B and C are equally spaced round the circumference of the hoop and X is vertically above the point O.*
- Calculate the length of XO.
- Find the angle, in degrees, between any string and the horizontal plane.
- Write down the size of angle AOB
- Calculate the length of AB.
- Find the angle between strings XA and XB.
*ABCDV is a solid glass pyramid. The base of the pyramid is a square of side 3.2 cm. The vertical height is 2.8 cm. The vertex V is directly above the centre O of the base.*
- Calculate the volume of the pyramid
- The glass weighs 9.3 grams per cm^3. Calculate the weight of the pyramid.
- Show that the length of the sloping edge VC of the pyramid is 3.6 cm
- Calculate the angle at the vertex, BVC
- Calculate the total surface are of the pyramid.
LaoshiSun, 06 Aug 2017 10:20:11 +0200https://ask.sagemath.org/question/38484/'object is not callable' error in sagetex (that doesn't occur in a worksheet)https://ask.sagemath.org/question/35766/object-is-not-callable-error-in-sagetex-that-doesnt-occur-in-a-worksheet/I'm generating random numbers to be presented in scientific notation for a quiz I'm typing. In testing this code works fine in a worksheet, but gives an error in a sagesilent block of my .tex document. Here's the code:
sci = {}
for index in range(1, 14): # Picks random coeffs for sci not.
places = ZZ.random_element(0, 4)
sci["co{0}".format(index)] = round(10*random(), places)
powe = {}
for index in range(1, 14): # Picks random powers for use.
powe["r{0}".format(index)] = ZZ.random_element(5, 10)
sci['co1']
sci['co2']
powe['r1']
powe['r2']
In the worksheet, those last four lines generate output like
3.0
5.566
7
8
But when I use that same code in the .tex document (without the last four lines), Sage returns this error before I can even call my numbers:
'module' object is not callable
My best guess is that rounding needs some package that the worksheet imports automatically but sagetex does not, but I'm afraid I don't know enough about what's really going on. Thank you for any help!mathochistMon, 28 Nov 2016 20:00:55 +0100https://ask.sagemath.org/question/35766/How to substitute a random sample of variables in Boolean Functionhttps://ask.sagemath.org/question/33995/how-to-substitute-a-random-sample-of-variables-in-boolean-function/ I want to make a function which generates randomly a Boolean function with **n** variables and then substitutes **k** of them with zero. I tried to get the list of terms of the function and then do the substitution which is certainly wrong.
def Pol_sub(n,k):
if k>n:
print("substitution can't be done")
else:
B=BooleanPolynomialRing(n,'x')
list=sorted((sample(xrange(0,n),k)))
f=B.random_element()
ls=f.terms()
print(f)
zero_vec=[0 for x in xrange(0,k)]
return(ls.subs({ls[list[i]]:zero_vec[i] for i in xrange(0,k)})) kristiSat, 02 Jul 2016 13:05:28 +0200https://ask.sagemath.org/question/33995/Converting sage output into static latex functionhttps://ask.sagemath.org/question/31414/converting-sage-output-into-static-latex-function/Hello!
I want to be able to use sagetex to do some work in sage, and then create a latex function with the result of that sage work, but without calling sage every time the function is called.
Here is an example of the current pseudo-code
\begin{sagesilent}
func1 = x - 3
func2 = x + 1
f = expand(func1*func2)
\end{sagesilent}
\newcommand{\foo}{\sage{f}}
Here, what would normally happen is sage silent runs sage, and creates the correct f = x^2 - 2x - 3. Then every time \foo is called, it reruns an instance of sage to go locate the definition of f in the sage file, and then sage will spit out the definition in text to \foo which then will display f. This is taking a lot of compute time unnecessarily, and when things get randomized it all goes to hell.
Is there any way to force a command to take in the (sage) definition when it's defined, and then save that definition as straight up text so that I don't have to rerun sage to go find the definition of f every time I want to call \foo?
Edit: It seems this could be accomplished if there is a way to define a latex command inside the sagesilent environment? From reading the sage doc it seems that this should be possible (there are examples doing it from a sage prompt) but I can't seem to figure out the correct syntax. Suggestions?Jason021Tue, 08 Dec 2015 17:05:53 +0100https://ask.sagemath.org/question/31414/random polytopeshttps://ask.sagemath.org/question/29819/random-polytopes/ Hi there,
Is there an easy way to generate random d-polytopes?
Thanks,
Guillermo Guillermo Pineda-VillavicencioThu, 08 Oct 2015 04:46:55 +0200https://ask.sagemath.org/question/29819/Random numbers in parallel calculationshttps://ask.sagemath.org/question/26046/random-numbers-in-parallel-calculations/ Assume I have a function that requires random number (noise) like:
@parallel
def foo(i):
print np.random.random()
4 sequential runs yield desired output:
for i in range(4):
foo(i)
0.961718217227
0.909042125122
0.736138778296
0.149902522071
But the parallel run calculates only one random value:
list(foo(range(4)))
0.633760965726
0.633760965726
0.633760965726
0.633760965726
[(((0),{}),None),(((2),{}),None),(((1),{}),None),(((3),{}),None)]
How do I properly generate random values from within parallel function?EugeneFri, 06 Mar 2015 14:33:37 +0100https://ask.sagemath.org/question/26046/How does one get Sage to make random choices?https://ask.sagemath.org/question/25783/how-does-one-get-sage-to-make-random-choices/ Like say in the middle of a code I compute a function value $f(x)$ and I knwo that $0 \leq f(x) \leq 1$. Now I want to write an if-then-else which will do one option with probability $f(x)$ and the other otion with probability $1-f(x)$. How does one make Sage do this?
Can somoen kindly show a template example to simulate this? phoenixMon, 09 Feb 2015 22:54:11 +0100https://ask.sagemath.org/question/25783/Generating random polynomials in R/Ihttps://ask.sagemath.org/question/24921/generating-random-polynomials-in-ri/I'm trying to generate random polynomials in ring R/I. Here's an example:
P.<x> = PolynomialRing(ZZ)
R = P.quotient(x**256 + 1)
I = R.ideal(g) # for some appropriate polynomial g
S = QuotientRing(R, I)
S.random_element()
Instead of this last command outputting a polynomial, it outputs a small integer. Looking through the sage code, the `QuotientRing_nc` class doesn't appear to be overloading `random_element`, so I guess the default `random_element` method from the `Ring` class is being called, which just outputs random integers.
Is there any way to generate random polynomials in `S`, or is that functionality not implemented currently?
Thanks.amalozWed, 19 Nov 2014 21:31:31 +0100https://ask.sagemath.org/question/24921/Fast (uniform) random integer generationhttps://ask.sagemath.org/question/23377/fast-uniform-random-integer-generation/I'm doing some largish experiments involving randomness, and I think random number generation may be the bottleneck. Is there a way to make the random number generator significantly faster without sacrificing the validity of results? I don't especially care that the RNG be cryptographically secure or anything like that.Anschel Schaffer-CohenFri, 11 Jul 2014 19:34:54 +0200https://ask.sagemath.org/question/23377/random selectionhttps://ask.sagemath.org/question/9804/random-selection/How I do randomly select a element in GO(n,RR)?canisvetusTue, 18 Feb 2014 05:16:19 +0100https://ask.sagemath.org/question/9804/Probability density function - multivariate random variablehttps://ask.sagemath.org/question/10872/probability-density-function-multivariate-random-variable/Hi experts!
I know that many of you are professional mathematicians. My question is about statcistics and sage:
given two independient random variables `X` and `Y` (with a probability density function `fX` and `fY`), and the multivariable random variable `A` defined by: `A=h(X,Y)`,
How can I obtain the explicit equation of probability density function of random varible `A`?
I only know that the join probability density fuction `fXY` is `fXY=fX*fY` (because there are independent).
Like you can see in the article
http://en.wikipedia.org/wiki/Probability_density_function
section 'Multiple variables' we can write the pdf of `A` using Dirac delta function.
Waiting for your answers.
Thans a lot!!mresimulatorWed, 01 Jan 2014 14:11:34 +0100https://ask.sagemath.org/question/10872/Random orbithttps://ask.sagemath.org/question/10585/random-orbit/Hi! I have to create a list for a random orbit [p1,p2,..pi] where each pi equals to the image of pi-1, and i have 3 différent functions that can be chosen randomly. I have to generate 50k points.miouchaThu, 19 Dec 2013 18:00:11 +0100https://ask.sagemath.org/question/10585/Create a new listhttps://ask.sagemath.org/question/10848/create-a-new-list/Hi! I have a work to do on Sage and I want to know how can I create a new list where I can put 50k values, so then I can show it after on a graphic. Also I have another question, how can i generate randomly a number between one and three? Thank you!miouchaThu, 19 Dec 2013 14:52:39 +0100https://ask.sagemath.org/question/10848/random number generator functionhttps://ask.sagemath.org/question/10802/random-number-generator-function/What is SAGE's equivalent of Mathematica's RandomReal[] function?Tom BurkeWed, 04 Dec 2013 22:28:11 +0100https://ask.sagemath.org/question/10802/Speed comparison with numerical arrays: sage, R, matlabhttps://ask.sagemath.org/question/10671/speed-comparison-with-numerical-arrays-sage-r-matlab/Dear all
I am a sage newbie coming from matlab, R, and Maple, and although I really like many features, I find that my sage code for handling numerical arrays is much more complex and much slower than the corresponding code in R and Matlab.
Here's an example:
# Simuating a sample path of standard Brownian motion
I want to simulate a random path of standard Brownian motion. The input is a vector of time points, and I want returned a (random) trajectory, sampled at these time points.
To do this I need: 1) Fast random number generation 2) Fast array operations: Diff, multiplication, and cumsum. I found that in sage I need to go through NumPy, so I wrote:
sage: import numpy
sage: # General routine to sample a Brownian motion on a time grid
sage: def rB(tvec):
sage: dt = numpy.diff(numpy.array(tvec))
sage: sdt = sqrt(dt)
sage: RNG = RealDistribution('gaussian',1)
sage: dB = sdt * numpy.array([RNG.get_random_element() for j in range(dt.__len__())],dtype=float)
sage: B1 = numpy.array([normalvariate(0,sqrt(tvec[0]))],dtype=float)
sage: B = numpy.cumsum(numpy.concatenate((B1,dB)))
sage: return(B)
I then time it, testing with 1 million time points:
sage: tvec = srange(0,1e3,1e-3)
sage: time B = rB(tvec)
I get a time of 3.5 seconds on my machine, a standard Laptop running Ubuntu, running sage from the shell. Using prun, I see that half of the time, roughly, is spent generating random numbers and the other half mainly constructing numerical arrays.
For comparison, the R code would be (here I assume that tvec[1]=0)
> tvec <- seq(0,1000,1e-3)
> system.time(B <- c(0,cumsum(rnorm(length(tvec)-1,sd=sqrt(diff(tvec))))))
which executes in 0.24 seconds. The matlab code would be
>> tvec = linspace(0,1e3,1e6+1);
>> tic;B = [0,cumsum(randn(1,length(tvec)-1) .* sqrt(diff(tvec)))];toc
which runs in 0.06 seconds.
You see that my sage code is not only clumsier, it is also between 10 and 100 times slower, so I guess I am doing something wrong.
I would really appreciate if you could point me in the direction of cleaner and faster code.
Cheers,
Uffe
Uffe_H_ThygesenMon, 28 Oct 2013 18:52:08 +0100https://ask.sagemath.org/question/10671/Numpy array or list of random signshttps://ask.sagemath.org/question/10468/numpy-array-or-list-of-random-signs/Hi experts!
How can I obtain a numpy array or list of 'N'random signs? for example:
[1, -1, 1, 1 , -1, -1, 1 , 1, 1]
where N = 9.
Waiting for your answers.
Thanks a lot!mresimulatorSat, 24 Aug 2013 18:28:40 +0200https://ask.sagemath.org/question/10468/motifs and subgraphshttps://ask.sagemath.org/question/10157/motifs-and-subgraphs/I'm counting the number of motifs (3-nodes isophormic class of connected subgraphs) in a random directed network. There are 13 of this. One is, for example S1={1 -> 2, 2 -> 3} and another one S2={1 -> 2, 2 -> 3, 1 -> 3}. They are two distinct motifs, and I wouldn't count a S1 when I actually find S2. The problem is that S1 is in S2, hence subgraph_search() finds a S1 in each S2 and all related functions inherit the problem (wrong counting, wrong iterator...).
Any idea how to resolve this issue? Similar things would happen for 4-nodes motifs and so on...
The code I used goes like:
import numpy
M1 = DiGraph(numpy.array([[0,1,0],[0,0,1],[0,0,0]])) #first motif
M5 = DiGraph(numpy.array([[0,1,1],[0,0,1],[0,0,0]])) #second motif
g = digraphs.RandomDirectedGNP(20,0.1) #a random network
l1 = []
for p in g.subgraph_search_iterator(M1): #search first motif
l1.append(p) #make a list of its occurences
l5 = []
for p in g.subgraph_search_iterator(M5): #the same for the second motif
l5.append(p)
gvdrMon, 27 May 2013 02:02:15 +0200https://ask.sagemath.org/question/10157/random seedhttps://ask.sagemath.org/question/10029/random-seed/How to start using random() and stop the process and then recover the random generation from the point where it stopped?
Example
set_random_seed(0)
some cycle calling random()
later
set_random_seed( ...where??... )
more steps of some cycle calling random()
PedroTue, 16 Apr 2013 11:08:28 +0200https://ask.sagemath.org/question/10029/Assigning students in groupshttps://ask.sagemath.org/question/9871/assigning-students-in-groups/I have a project with 60 students and 6 teachers. I'd like to know if it is possible to use Matrix and Permutation functions in Sage to assign those 60 students in 6 groups. There would be 6 sessions (a month each). Each student has to work once with each teacher and avoid being in the same group of students (as much as possible).
Thank you.KaiserfilkSun, 03 Mar 2013 18:03:06 +0100https://ask.sagemath.org/question/9871/sage samplehttps://ask.sagemath.org/question/9713/sage-sample/hi i have a problem to solve, sorry if my english is bad :D:
I have to calculate function pi(x) that gives me a number of prime-numbers in range from zero to x.
x=10^10 and i have to take a sample of n random numbers from 1 to x and test how much of them are primes. then from that part(proportion) i have to calculate pi(x).
another question is : what amount of sample i have to take so that relative error, when i calculate number od prime number by prime_pi(10^10), falls below 1%.
if you have any question just ask and I will try to answer them.
thank you soo much :D :D :D
blah blahWed, 16 Jan 2013 14:54:10 +0100https://ask.sagemath.org/question/9713/Generating random normal vectors and matriceshttps://ask.sagemath.org/question/9274/generating-random-normal-vectors-and-matrices/I'm new to sage, and am looking for the best ways to generate matrices and vectors with the following properties:
- Matrices with independent normal entries. The default distribution of entries in matrices generated by random_matrix seems to be uniform over [-1,1]. Can that be changed?
- Random (normal) vectors with fixed sparsity, in the sense that only a given number of the entries are non-zero.
Thanks for any assistance.staffordTue, 28 Aug 2012 22:29:21 +0200https://ask.sagemath.org/question/9274/Problem calling np.random.multinomial from notebookhttps://ask.sagemath.org/question/8972/problem-calling-nprandommultinomial-from-notebook/According to np.random.multinomial? this is what I should expect
np.random.multinomial(20, [1/6.]*6, size=2)
array([[3, 4, 3, 3, 4, 3],
[2, 4, 3, 4, 0, 7]])
However when I type the same thing in notebook I get an error. The same command works fine in my system python. In sage notebook it works when I drop the argument size=2. This seems to be problem with sage notebook. Any suggestions?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "_sage_input_48.py", line 10, in <module>
exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("aW1wb3J0IG51bXB5IGFzIG5wCm5wLnJhbmRvbS5tdWx0aW5vbWlhbCgxMDAsIFsxLzIuMF0qMixzaXplPTMp"),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
File "", line 1, in <module>
File "/tmp/tmpARgtW7/___code___.py", line 4, in <module>
exec compile(u'np.random.multinomial(_sage_const_100 , [_sage_const_1 /_sage_const_2p0 ]*_sage_const_2 ,size=_sage_const_3 )
File "", line 1, in <module>
File "mtrand.pyx", line 4050, in mtrand.RandomState.multinomial (numpy/random/mtrand/mtrand.c:17809)
File "element.pyx", line 1305, in sage.structure.element.RingElement.__add__ (sage/structure/element.c:11569)
File "coerce.pyx", line 797, in sage.structure.coerce.CoercionModel_cache_maps.bin_op (sage/structure/coerce.c:7467)
TypeError: unsupported operand parent(s) for '+': 'Integer Ring' and '<type 'tuple'>'
ShashankTue, 15 May 2012 19:37:13 +0200https://ask.sagemath.org/question/8972/how to calculate in SAGE the cumulative distribution function of a "stable distribution"?https://ask.sagemath.org/question/8874/how-to-calculate-in-sage-the-cumulative-distribution-function-of-a-stable-distribution/A stable distribution, defined in [wiki](http://en.wikipedia.org/wiki/L%C3%A9vy_skew_alpha-stable_distribution) is basically defined by,
> In probability theory, a random variable is said to be stable (or to have a stable distribution) if it has the property that a linear combination of two independent copies of the variable has the same distribution, up to location and scale parameters.
As far as I know, the family of stable
distributions is defined by four
parameters: mu, c, alpha and beta. I
need to generate random numbers
according to a given stable
distribution, that is, to a given
choice of the parameters of the stable
distribution family.
How can it be done in SAGE? Is there some "statistical package" which provides this?
Best regards.juanpoolWed, 11 Apr 2012 18:56:26 +0200https://ask.sagemath.org/question/8874/How do I generate a random number according to the binomial distribution?https://ask.sagemath.org/question/8848/how-do-i-generate-a-random-number-according-to-the-binomial-distribution/I would like to generate a random integer according to the binomial distribution. That is, I would like to generate a Bin(n,p) random value. That's number between 0 and n in which the probability we get the value k is `C(n,k)p^k(1-p)^(n-k)`.
Here is an inefficient method (which requires n calls to `random()` ):
def bin_rv(n,p=0.5):
"""
Generate a binomial random variable with parameters n,p.
"""
return sum( random() < p for _ in range(n))
Is there a better way to do this (already built into Sage, I hope)?
(In Matlab, this can be done via the `binord` function and in R with the `rbinom` function.)Ed ScheinermanMon, 02 Apr 2012 15:50:18 +0200https://ask.sagemath.org/question/8848/