So im trying to create an function that creates a Stochastic matrix (a square matrix where each column summing is 1), it tried dividing every element of the column to the summming of it ,but sometimes it seems to throw unexpected values. The values of the matrix need to have 2 decimal places so i cannot change that. What am i doing wrong?
Some of the tests i did: enter image description here enter image description here In the second one, the summing of some of the columns isn't 1.
#include <iostream>
#include <cmath> //fmod
#include <math.h> //round()
using namespace std;
template<typename T>
T** crear_matriz(int filas, int columnas) {
T** matriz = new T * [filas];
for (size_t i = 0; i < filas; i++) {
matriz[i] = new T[columnas];
}
return matriz;
}
template<typename T>
void borra_matriz(T** matrix, int filas) {
for (size_t i = 0; i < filas; i++) {
delete[] matrix[i];
}
delete[] matrix;
}
double** CrearMatrizEstocastica(double ** matrix,int rows, int column) {
for (int j = 0; j < column; j++) {
double columnsum = 0;
for (int i = 0; i < rows; i++) {
double random_num = static_cast<double>(rand()) / RAND_MAX;
matrix[i][j] = random_num;
columnsum += matrix[i][j];
}
for (int i = 0; i < rows; i++) {
matrix[i][j] /= columnsum;
matrix[i][j] = round(matrix[i][j] * 10) / 10;
}
}
cout << "Schocastic Matrix created!" << endl;
return matrix;
}
int main()
{
srand(time(NULL));
double** MatrizEstocastica=crear_matriz<double>(4,4) ;
MatrizEstocastica = CrearMatrizEstocastica(MatrizEstocastica,4,4);
MostrarMatrizEstocastica(MatrizEstocastica, 4, 4);
borra_matriz<double>(MatrizEstocastica , 4);
return 0;
}