• We've upgraded our forums. Please post any issues/requests in this thread.

Need help: rand() C always returns 0

Joined
Nov 20, 2013
Messages
2,513 (1.69/day)
Likes
2,604
Location
Kiev, Ukraine
System Name Evil Midget
Processor i3-6100
Motherboard MSI B150I PRO AC
Cooling Noctua NH-L9i
Memory 2x8GB Kinkston HyperX DDR4-2133 CL14
Video Card(s) ASUS GTX950 MINI
Storage Samsung XP941, Sandisk X400 512GB
Display(s) Samsung U24E590D (4K/UHD)
Case LianLi Q11B
Audio Device(s) Int.
Power Supply SeaSonic 450W 80+ GOLD
Mouse Logitech G5
Keyboard Zalman K500 modded
Software Windows 10
Benchmark Scores Can fit into a backpack =)
#1
I'm using Code::Blocks to write the code and rand() function always return 0.
I tried to plant the seed with srand(time(NULL)), srand(opm_get_wtime()) and at least 10 different other methods, but it does not work...

Does anybody know how to fix this?

The general outline of my code looks like this:

Code:
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>

int main()
{
    int toss;
    int number_in_circle = 0;
    int number_of_tosses = 10;
    double distance_squared;
    double x;
    double y;
    srand(time(NULL));
    for (toss=0;toss<number_of_tosses;toss++)
    {
        x = rand()/RAND_MAX - 1;
        y = rand()/RAND_MAX - 1;
        printf("x=%f",x);
        printf("y=%f\r\n",y);
        distance_squared = x * x + y * y ;
        if ( distance_squared <= 1) number_in_circle++;
    }
    int pi_estimate = 4*number_in_circle /((double) number_of_tosses );
    printf("Pi estimate: %d",pi_estimate);
    return 0;
}
 

W1zzard

Administrator
Staff member
Joined
May 14, 2004
Messages
17,068 (3.44/day)
Likes
17,975
Processor Core i7-4790K
Memory 16 GB
Video Card(s) GTX 1080
Display(s) 30" 2560x1600 + 19" 1280x1024
Software Windows 7
#2
what's with the -1 there? and why isn't it in ( ) together with RAND_MAX ?
also rand() returns an int, which you might want to cast to a double, so that division works as you assume it to work :)
 
Joined
Nov 20, 2013
Messages
2,513 (1.69/day)
Likes
2,604
Location
Kiev, Ukraine
System Name Evil Midget
Processor i3-6100
Motherboard MSI B150I PRO AC
Cooling Noctua NH-L9i
Memory 2x8GB Kinkston HyperX DDR4-2133 CL14
Video Card(s) ASUS GTX950 MINI
Storage Samsung XP941, Sandisk X400 512GB
Display(s) Samsung U24E590D (4K/UHD)
Case LianLi Q11B
Audio Device(s) Int.
Power Supply SeaSonic 450W 80+ GOLD
Mouse Logitech G5
Keyboard Zalman K500 modded
Software Windows 10
Benchmark Scores Can fit into a backpack =)
#3
what's with the -1 there? and why isn't it in ( ) together with RAND_MAX ?
also rand() returns an int, which you might want to cast to a double, so that division works as you assume it to work :)
Thx W1zzard! Had to change the type to int and it worked.
The actual calculation is:
Code:
x = 2*rand()/RAND_MAX - 1;
I'm trying to generate numbers between -1 and 1 for multithreaded version of Monte Carlo algorithm.