Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/graphs/graph_generators_pyx.pyx
4056 views
1
r"""
2
Common graphs and digraphs generators (Cython)
3
4
AUTHORS:
5
6
- David Coudert (2012)
7
"""
8
9
10
################################################################################
11
# Copyright (C) 2012 David Coudert <[email protected]>
12
#
13
# Distributed under the terms of the GNU General Public License (GPL)
14
# http://www.gnu.org/licenses/
15
################################################################################
16
17
from sage.misc.randstate cimport random
18
from sage.functions.log import ln
19
20
def RandomGNP(n, p, directed = False, loops = False):
21
r"""
22
Returns a random graph or a digraph on `n` nodes. Each edge is inserted
23
independently with probability `p`.
24
25
INPUTS:
26
27
- ``n`` -- number of nodes of the digraph
28
29
- ``p`` -- probability of an edge
30
31
- ``directed`` -- is a boolean indicating whether the random graph is
32
directed or undirected (default).
33
34
- ``loops`` -- is a boolean set to True if the random digraph may have
35
loops, and False (default) otherwise. This value is used only when
36
``directed == True``.
37
38
REFERENCES:
39
40
.. [1] P. Erdos and A. Renyi. On Random Graphs, Publ. Math. 6, 290 (1959).
41
42
.. [2] E. N. Gilbert. Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
43
44
EXAMPLE::
45
46
sage: from sage.graphs.graph_generators_pyx import RandomGNP
47
sage: set_random_seed(0)
48
sage: D = RandomGNP(10, .2, directed = True)
49
sage: D.num_verts()
50
10
51
sage: D.edges(labels=False)
52
[(0, 2), (0, 5), (1, 5), (1, 7), (4, 1), (4, 2), (4, 9), (5, 0), (5, 2), (5, 3), (5, 7), (6, 5), (7, 1), (8, 2), (8, 6), (9, 4)]
53
54
TESTS::
55
56
sage: abs(mean([RandomGNP(200,.2).density() for i in range(30)])-.2) < .001
57
True
58
sage: RandomGNP(150,.2, loops = True)
59
Traceback (most recent call last):
60
...
61
ValueError: The 'loops' argument can be set to True only when 'directed' is True.
62
"""
63
from sage.graphs.graph import Graph, DiGraph
64
65
cdef int i, j
66
67
# according the sage.misc.randstate.pyx documentation, random
68
# integers are on 31 bits. We thus set the pivot value to p*2^31
69
cdef float RAND_MAX_f = (1<<31)*1.0
70
cdef int pp = int(round(p*(1<<31)))
71
72
if directed:
73
G = DiGraph(loops = loops)
74
else:
75
G = Graph()
76
if loops:
77
raise ValueError("The 'loops' argument can be set to True only when 'directed' is True.")
78
G.name('Random'+('Directed' if directed else '')+'GNP(%s,%s)'%(n,p))
79
80
G.add_vertices(range(n))
81
82
# Standard random GNP generator for Graph and DiGraph
83
for 0 <= i < n:
84
for (0 if directed else i+1) <= j < n:
85
if random() < pp:
86
G.add_edge(i,j)
87
88
return G
89
90