views:

24

answers:

1

Hiya im trying to write a code for basic 1D Monte-Carlo integration. To do so I need a list of pseudo-random numbers which I can then input into a function (stored in another subroutine). I've given the list of random numbers a pointer but when I try to dereference it in main I get "error: incompatible types when assigning to type ‘double[11]’ from type ‘double’ " . Could anyone tell me where I'm going wrong? My code can be found here:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#ifndef RAND_MAX
#define RAND_MAX 2147483648
#endif
#define N 10

double function(double x);
double* rdm(void);

void main(void)
{
   double* Random_number_list;
   int i;
   double sum = 0.0, sum2 = 0.0, X[N+1],S, Random_number_list2[N + 1];
   double F[N+1], lower, upper, avg, avg2;
   printf("Lower Bound:  ");
   scanf("%lf", &lower);
   printf("Upper Bound:  ");
   scanf("%lf", &upper);

   Random_number_list2 = *Random_number_list;

   for (i = 0; i <= N; i++) {
      X[i] = ((upper - lower)*Random_number_list2[i]) + lower;
      F[i] = function(X[i]);
      sum = sum + F[i];
      sum2 = sum2 + (F[i] * F[i]);
   }
   avg = sum / N;
   avg2 = sum2 / N;
   S = (upper - lower) * (avg + sqrt((avg2 - (avg * avg)) / N));
   printf("The Monte Carlo approximation is %lf\n", S);  
}

double function(double x)
{
   double y;
   y = sin (x);
   return y;
}

double* rdm(void)
{
   double* Random_number_list = calloc(N + 1, sizeof(double));
   int i;

   srand(time(NULL));
   for (i = 1; i <= N; i++) {
      Random_number_list[i] = (float) rand() / (float) RAND_MAX;
   }
   return Random_number_list;
}

Many Thanks. Jack Medley

+4  A: 

Given:

 int * a;
 int b[5];

then you can write:

 a = b;  // copying a pointer, same as a = &b[0];

However, you cannot write:

 b = a;  // b's memory is allocated, you cannot swap it out.

Which means, lose Random_number_list2, and work with just Random_number_list.

You want:

 double* Random_number_list = rdm();

and later

 // added space, so it's clearer you're multiplying and not dereferencing.
 X[i] = ((upper - lower) * Random_number_list[i]) + lower;
James Curran
Sorry just to clarify I want:double* Random_number_list = rdm();when I'm declaring in main()?
Jack Medley
Ah got it Thank you kindly
Jack Medley