Click here to Skip to main content
14,884,185 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
#include <iostream>
#include "mt.h"

using namespace std;

int main (int argc, char** argv) {
    int N = 1000000;
    double ran[N];
    double mean = 0.0;

    // Initialize a Mersenne Twister
    MersenneTwister mt;

    // Take N draws from Uniform(0,1)
    for (int i = 0; i < N; i++) {
        ran[i] = mt.random();

    // Calculate the mean
    for (int i = 0; i < N; i++) {
        mean += ran[i];
    mean /= N;

    cout << "Sample mean of " << N << "draws:" << mean << endl;

    return EXIT_SUCCESS;

What I have tried:

i have marsenne twister code and i want it in c
Updated 10-Jan-21 0:57am

Page 1 of 3

No their is no online converter. In C you havent any classes and so you must decompose your MersenneTwister class.

A possible solution is, that all data members from that class becoming an struct, and your functions get a pointer to that struct as input.

struct MersenneTwister {
  int data;
  // and so on
} _MersenneTwister;

void init( _MersenneTwister* twister ); // set some default values
void print( _MersenneTwister* twister ); //use
void random( _MersenneTwister* twister ); //

The out you must replace with print. Look at the sample code to understand the usage.
There seem to be some tools, but probably not to your liking, see this: How to convert C++ Code to C - Stack Overflow[^]
An online version (doubt if it works): Test Drive Comeau C/C++ Online[^]
There are 2 options. The first one is given by KarstenK using structs.
The second is to rewrite the code using C. The problem is that C++ is an object oriented language, so functions, variable and other classes or objects are encapsulated in classes with public and private parts and submitted to inheritances so as long as the structure is totally different so there is not a direct way to make an automatic system that makes that conversion unless the program is very simple and fulfill a number of conditions
Converting your code to C is almost trivial.
Less trivial is providing a Marsenne twister implementation.
Luckily you may find some C implentations freely available on the web. See, for instance: Mersenne Twister in C, C++, C#[^].
Nelek 6-Oct-18 15:13pm
You got fooled by a spammer... the question is over a year old ;)
CPallini 6-Oct-18 16:09pm
Yep. You are right.

Page 1 of 3
1 2 3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900