Path: blob/master/sage/graphs/graph_generators_pyx.pyx
4056 views
r"""1Common graphs and digraphs generators (Cython)23AUTHORS:45- David Coudert (2012)6"""789################################################################################10# Copyright (C) 2012 David Coudert <[email protected]>11#12# Distributed under the terms of the GNU General Public License (GPL)13# http://www.gnu.org/licenses/14################################################################################1516from sage.misc.randstate cimport random17from sage.functions.log import ln1819def RandomGNP(n, p, directed = False, loops = False):20r"""21Returns a random graph or a digraph on `n` nodes. Each edge is inserted22independently with probability `p`.2324INPUTS:2526- ``n`` -- number of nodes of the digraph2728- ``p`` -- probability of an edge2930- ``directed`` -- is a boolean indicating whether the random graph is31directed or undirected (default).3233- ``loops`` -- is a boolean set to True if the random digraph may have34loops, and False (default) otherwise. This value is used only when35``directed == True``.3637REFERENCES:3839.. [1] P. Erdos and A. Renyi. On Random Graphs, Publ. Math. 6, 290 (1959).4041.. [2] E. N. Gilbert. Random Graphs, Ann. Math. Stat., 30, 1141 (1959).4243EXAMPLE::4445sage: from sage.graphs.graph_generators_pyx import RandomGNP46sage: set_random_seed(0)47sage: D = RandomGNP(10, .2, directed = True)48sage: D.num_verts()491050sage: D.edges(labels=False)51[(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)]5253TESTS::5455sage: abs(mean([RandomGNP(200,.2).density() for i in range(30)])-.2) < .00156True57sage: RandomGNP(150,.2, loops = True)58Traceback (most recent call last):59...60ValueError: The 'loops' argument can be set to True only when 'directed' is True.61"""62from sage.graphs.graph import Graph, DiGraph6364cdef int i, j6566# according the sage.misc.randstate.pyx documentation, random67# integers are on 31 bits. We thus set the pivot value to p*2^3168cdef float RAND_MAX_f = (1<<31)*1.069cdef int pp = int(round(p*(1<<31)))7071if directed:72G = DiGraph(loops = loops)73else:74G = Graph()75if loops:76raise ValueError("The 'loops' argument can be set to True only when 'directed' is True.")77G.name('Random'+('Directed' if directed else '')+'GNP(%s,%s)'%(n,p))7879G.add_vertices(range(n))8081# Standard random GNP generator for Graph and DiGraph82for 0 <= i < n:83for (0 if directed else i+1) <= j < n:84if random() < pp:85G.add_edge(i,j)8687return G888990