[READ-ONLY] Mirror of https://github.com/shuuji3/python-extension-twister. Experimental Python C extension to generate random numbers by using Mersenne twister
0

Configure Feed

Select the types of activity you want to include in your feed.

python-extension-twister / src / twistermodule.c
2.6 kB 108 lines
1#include <Python.h> 2 3#include <stdio.h> 4#include <time.h> 5#include "mt19937ar/mt19937ar.h" 6 7/** 8 * 整数の乱数を num 個 print する関数 9 * @param num print する乱数の数を指定する 10 */ 11void print_rand_int(int num) { 12 // Print header 13 printf("# print %d random int\n", num); 14 fflush(stdout); 15 16 // Print rand 17 for (int i = 0; i < num; i++) { 18 printf("%10lu ", genrand_int32()); 19 if (i % 5 == 4) printf("\n"); 20 } 21 printf("\n"); 22 fflush(stdout); 23} 24 25/** 26 * [0, 1) の乱数を num 個 print する関数 27 * @param num print する乱数の数を指定する 28 */ 29void print_rand(int num) { 30 // Print header 31 printf("# print %d random numbers\n", num); 32 fflush(stdout); 33 34 // Print rands 35 for (int i = 0; i < num; i++) { 36 printf("%10.8f ", genrand_real2()); 37 if (i % 5 == 4) printf("\n"); 38 } 39 printf("\n"); 40 fflush(stdout); 41} 42 43/** 44 * print_rand_int() を実行する Python メソッド 45 */ 46static PyObject * 47twister_print_rand_int(PyObject *self, PyObject *args) { 48 int num = 10; 49 if (!PyArg_ParseTuple(args, "|l", &num)) { 50 return NULL; 51 } 52 print_rand_int(num); 53 Py_RETURN_NONE; 54} 55 56/** 57 * print_rand() を実行する Python メソッド 58 */ 59static PyObject * 60twister_print_rand(PyObject *self, PyObject *args) { 61 int num = 10; 62 if (!PyArg_ParseTuple(args, "|l", &num)) { 63 return NULL; 64 } 65 print_rand(num); 66 Py_RETURN_NONE; 67} 68 69/** 70 * 乱数を1つ生成する Python メソッド 71 */ 72static PyObject * 73twister_random(PyObject *self, PyObject *args) { 74 return PyFloat_FromDouble(genrand_real2()); 75} 76 77/** 78 * 拡張モジュールのメソッドの定義 79 */ 80static PyMethodDef TwisterMethods[] = { 81 {"print_rand_int", twister_print_rand_int, METH_VARARGS, "Print random int num times."}, 82 {"print_rand", twister_print_rand, METH_VARARGS, "Print random x in [0, 1) num times."}, 83 {"random", twister_random, METH_VARARGS, "Generate a random number x in [0, 1)."}, 84 {NULL, NULL}, 85}; 86 87/** 88 * 拡張モジュールの定義 89 */ 90static struct PyModuleDef twistermodule = { 91 PyModuleDef_HEAD_INIT, 92 "twister", 93 "Generate random numbers by using Mersenne twister.", 94 -1, 95 TwisterMethods, 96}; 97 98/** 99 * モジュール読み込み時に行われる初期化処理 100 * @return 101 */ 102PyMODINIT_FUNC 103PyInit_twister(void) { 104 // 現在時刻をシードに与えて乱数を初期化する 105 init_genrand((unsigned long) time(NULL)); 106 107 return PyModule_Create(&twistermodule); 108}