I have two questions regarding c
#1
if I have value(initialize a variable with a value) inside a block, like { }
then how is it different than the value outside that block, but within the same function

why does the value inside the block doesnt retain the old value outside the {}

#2 how can I make a biased random number generator.
like if I give a probability it will generate numbers biased to that

Recommended Answers

All 4 Replies

1) I'm not sure what you're asking. Are you talking about hiding a variable by using another variable of the same name in a nested scope?

#include <stdio.h>

int main ( void )
{
  int foo = 10;

  {
    int foo = 20;

    printf ( "foo = %d\n", foo );
  }

  return 0;
}

2) It depends on the bias you want and the range you want. An easy way for smaller ranges is to fill an array with the values you want, but increase the number of certain values that you want to be more probable. Then pick a random index from that array:

#include <stdio.h>

#define length(a) ( sizeof (a) / sizeof *(a) )

int main ( void )
{
  /* 5 is four times more probable */
  int a[] = {0,1,2,3,4,5,5,5,5,6,7,8,9};
  int freq[10] = {0};
  int i;

  for ( i = 0; i < 100000; i++ )
    ++freq[a[rand() % length ( a )]];

  puts ( "Value\tFrequency" );

  for ( i = 0; i < 10; i++ )
    printf ( "%d\t%d\n", i, freq[i] );

  return 0;
}

You should get about 7,500 for every number except 5, which should be around 30,000.

Thanks for the anwers

The first one shows that the value of variable is only retained in btween { and }
something like a local scope.

for the second one I am thinking something like a coin toss that is based on a probability

int BinomTrial(int k, float p)
{
int heads=0,i;
float coin;
//float p;
for(i=0;i<k;i++)
{
coin=0;
coin=((rand()%2)+1);
coin=coin*(1+p);
//coin=coin%2;
printf("%f\n",coin);

if(coin>(1+p))heads++;
}
 return heads;
}

how do I make the coin such that if I increase value of p, the chances of getting head increases.
just multiplying output of rand with 1+p isnt helping

A coin toss is pretty easy as you can turn it into a true or false formula:

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

int flip ( double probability )
{
  if ( probability < 0 )
    return 0;
  else if ( probability > 1 )
    return 1;

  return rand() <= ( RAND_MAX + 1.0 ) * probability - 0.5;
} 

int main ( void )
{
  int freq[2] = {0};
  int i;

  for ( i = 0; i < 100000; i++ )
    ++freq[flip ( .7 )];

  puts ( "Value\tFrequency" );

  for ( i = 0; i < 2; i++ )
    printf ( "%d\t%d\n", i, freq[i] );

  return 0;
}

thnkas, line #11 was extreamly helpful

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.