Click here to Skip to main content
14,449,309 members
Rate this:
Please Sign up or sign in to vote.
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;
    mt.print();

    // 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
Posted
Updated 24-Dec-19 3:26am
v3
Page 1 of 2

Rate this:
Please Sign up or sign in to vote.

Solution 1

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;

//prototyping
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.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

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[^]
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 3

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
   
Rate this:
Please Sign up or sign in to vote.

Solution 8

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#[^].
   
Comments
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 2
1 2

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100