简体   繁体   中英

Matrix Multiplication of random numbers using rand() function

Here is the code for matrix multiplication of random numbers using rand() function. The output of the program gives very large values as matrix elements.

Why not any small random numbers not generated??

This is the output when N=3

Enter the value of N : 3

Final Matrix :

259448206-96933429-936226671  
-409898077185182340844598571  
-1916994436-653447116470937338   

Program:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
    time_t t;
    int **ptr1, **ptr2, **ptr3;
    int N, col1, row2, col2;
    srand ((unsigned) time (&t));
    int i, j, k;
    printf ("\nEnter the value of N : ");
    scanf ("%d", &N);
    ptr1 = (int **) malloc (sizeof (int *) * N);
    ptr2 = (int **) malloc (sizeof (int *) * N);
    ptr3 = (int **) malloc (sizeof (int *) * N);

    for (i = 0; i < N; i++)
        ptr1[i] = (int *) malloc (sizeof (int) * N);
    for (i = 0; i < N; i++)
        ptr2[i] = (int *) malloc (sizeof (int) * N);
    for (i = 0; i < N; i++)
        ptr3[i] = (int *) malloc (sizeof (int) * N);

    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            ptr1[i][j] = rand ();
        }
    }

    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            ptr2[i][j] = rand ();
        }
    }

    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            ptr3[i][j] = 0;
            for (k = 0; k < N; k++)
                ptr3[i][j] = ptr3[i][j] + ptr1[i][k] * ptr2[k][j];
        }
    }

    /* Printing the contents of third matrix. */

    printf ("\n\nFinal Matrix :");
    for (i = 0; i < N; i++) {
        printf ("\n\t");
        for (j = 0; j < N; j++)
            printf ("%4d", ptr3[i][j]);
    }

    printf ("\n");
    return (0);
}

Use the modulo operator to get smaller values (eg rand()%100). While it is slightly non-uniformly distributed that way this should not be an issue here. – Ctx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM