Why do I receive this error when generating a random float? - c

Trying to generate a psuedo-random float btwn 0 and 1. Getting this error when I run the code:
‘RAND_MAX’ undeclared (first use in this function)
#include <stdio.h>
#include <time.h>
int main(test, numpoints, numtrials, dimension){
//generate a random number
srand(time(NULL));
float r = (float)(rand()/RAND_MAX +1);
printf("%.6f", r);
printf("\n");
}

To use RAND_MAX in C, you need to include its header:
#include <stdlib.h>
rand()/RAND_MAX is an integer division, if you want floating division, you should covert it to float first, then divide: (float)(rand()) / RAND_MAX
You need to define your main as:
int main ( int arc, char **argv )

RAND_MAX is within stdlib. You'll need to include it.
#include <stdlib.h>

(rand() / RAND_MAX) is an integer division, and will equal zero. You then add 1, and then convert to float, giving you 1.0. If you want floating division, you have to covert first, then divide: (float)(rand()) / RAND_MAX . . .
Plus, you're not including stdlib, and your arguments to main are wrong.

Try importing stdlib.h. Thats what is needed in C++ but I am not entirely sure about C.

Related

Random number generator PCG library. How to generate float numbers set within a range. Working example in c language

For example, we can use internal rand(), but it is the worst choice:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float randoms(float min, float max)
{
return (float)(rand())/RAND_MAX*(max - min) + min;
}
int main()
{
srand((unsigned int)time(0));
printf("%f\n",randoms(-100.001, 100.001));
return 0;
}
I've searched, but not found any working example of PCG library for float numbers.
In the answer I would like to share my own experience of using PCG random library to generate float numbers within a fixed range. Previously I've used arc4random library for this goal, but PCG is simpler and has no complicated dependencies.
How to generate float numbers set within a range(?)
Using various random functions can improve the random properties of integers generated. The application of those integers to make a float has other pitfalls not address by OP regardless of the random function. Also see #Serge Ballesta.
The simplistic use of the following risks generating a value outside the range [min...max]
float retval = (float)some_rand()/SOME_RAND_MAX*(max - min) + min;
The 2 conversion of the 2 integers to float incur rounding. float /,*,-,* each can contribute 4 more roundings. Given that min/max may come in many valid combinations, it is prudent to guard against an out-of-range retval
float retval;
assert(min < max); // may want to assert min/max are finite too
do {
retval = 1.0f*some_rand()/SOME_RAND_MAX*(max - min) + min;
} while (!(retval >= min && retval <= max));
return retval;
Note that the setting of FLT_EVAL_METHOD complicates any assessment as some calculations may be conducted as double/long double.
Potential losses of desired random properties:
The use of pcg32_random_r() versus rand() does provide numbers with more attractive integer random properties, yet those improved attributes are reduced with casual floating-point code.
(Assume binary32 for float)
Consider how the following can uniformly generate values in the range [0...224] yet values larger than that, it will be only even numbers. It becomes spottier with larger numbers up to (float)UINT32_MAX. This would be acceptable for another function that was now to return that value, but the scaling of *(max - min) + min redistributes those values in a way that can become very non-uniform.
(float)pcg32_random_r(...);
A simple way to address some of these short comings is to use higher precision like double math within float randoms(float min, float max), yet that approach does not help with long double randomsL(long double min, long double max)
You PCG will generate some number of random bits. Let's say that's 32. A double precision float has 53 bits of significand, so you'll need more than one call. So, call the function twice, and pack the two calls into a 64-bit integer:
int64_t x = (pcg32() << 32) | pcg32();
Then divide that integer down to the desired range (this is the signed -100...100 version):
double r = ((double)x * 100.0) / 9223372036854775808.0; // 2**63
// main.c
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
// PCH library headers
#include "pcg_variants.h"
#include "entropy.h" // Wrapper around /dev/random
int main(int argc, char** argv)
{
pcg32_random_t rng;
// Seed with external entropy
uint64_t seeds[2];
entropy_getbytes((void*)seeds, sizeof(seeds));
pcg32_srandom_r(&rng, seeds[0], seeds[1]);
for (int i = 0; i < 10; ++i)
{
uint32_t random_unsigned_integer = pcg32_random_r(&rng);
float max = 100.001;
float min = -100.001;
float q = (float)(random_unsigned_integer)/((float)UINT32_MAX)*(max - min) + min;
// Shows 10 float numbers in specified range.
printf("%.6f\n", q);
}
return 0;
}
Compile:
gcc -std=c11 -o pcg_float main.c

Initializing 2D array with math declaration [duplicate]

This question already has answers here:
Why is my power operator (^) not working?
(11 answers)
Closed 7 years ago.
So in python, all I have to do is
print(3**4)
Which gives me 81
How do I do this in C? I searched a bit and say the exp() function, but have no clue how to use it, thanks in advance
You need pow(); function from math.h header.
syntax
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
Here x is base and y is exponent. result is x^y.
usage
pow(2,4);
result is 2^4 = 16. //this is math notation only
// In c ^ is a bitwise operator
And make sure you include math.h to avoid warning ("incompatible implicit declaration of built in function 'pow' ").
Link math library by using -lm while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.
you can use pow(base, exponent) from #include <math.h>
or create your own:
int myPow(int x,int n)
{
int i; /* Variable used in loop counter */
int number = 1;
for (i = 0; i < n; ++i)
number *= x;
return(number);
}
#include <math.h>
printf ("%d", (int) pow (3, 4));
There's no operator for such usage in C, but a family of functions:
double pow (double base , double exponent);
float powf (float base , float exponent);
long double powl (long double base, long double exponent);
Note that the later two are only part of standard C since C99.
If you get a warning like:
"incompatible implicit declaration of built in function 'pow' "
That's because you forgot #include <math.h>.
For another approach, note that all the standard library functions work with floating point types. You can implement an integer type function like this:
unsigned power(unsigned base, unsigned degree)
{
unsigned result = 1;
unsigned term = base;
while (degree)
{
if (degree & 1)
result *= term;
term *= term;
degree = degree >> 1;
}
return result;
}
This effectively does repeated multiples, but cuts down on that a bit by using the bit representation. For low integer powers this is quite effective.
just use pow(a,b),which is exactly 3**4 in python
Actually in C, you don't have an power operator. You will need to manually run a loop to get the result. Even the exp function just operates in that way only. But if you need to use that function, include the following header
#include <math.h>
then you can use pow().

geometric series in c, wrong solution

I'm getting a wrong solution for this series: (-1/4)^(n+1)*(z-1)^n
For |z-1|<4 should the series tend to converge to -1/3+z
For z=0.5 should be the solution -2/7, but if i try to plot with c, the result is 0...
Here is my code:
#include <stdio.h>
#include <math.h>
int main(){
double sum=0;
int n;
for(n=0;n<=100000;n++){
sum+=pow((-1/4),(n+1)) * pow((0.5-1),n);
}
printf("sum= %f\n",sum);
}
Problem right here:
sum+=pow((-1/4),(n+1)) * pow((0.5-1),n);
-1 is an integer literal, and so is 4; hence, (-1/4) is -0, and not -0.25 (which was probably what you wanted to use). Use floating point literals like -1.0 if you want them in C!
-1/4 will result to 0 as its an integer division, use floats instead:
(float)-1/4
1/4 refers to the euclidian division hence 0 obtained.
Use sum+=pow((-1.0/4.0),(n+1)) * pow((0.5-1),n); and you get the good results sum= -0.285714

To the power of in C? [duplicate]

This question already has answers here:
Why is my power operator (^) not working?
(11 answers)
Closed 7 years ago.
So in python, all I have to do is
print(3**4)
Which gives me 81
How do I do this in C? I searched a bit and say the exp() function, but have no clue how to use it, thanks in advance
You need pow(); function from math.h header.
syntax
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
Here x is base and y is exponent. result is x^y.
usage
pow(2,4);
result is 2^4 = 16. //this is math notation only
// In c ^ is a bitwise operator
And make sure you include math.h to avoid warning ("incompatible implicit declaration of built in function 'pow' ").
Link math library by using -lm while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.
you can use pow(base, exponent) from #include <math.h>
or create your own:
int myPow(int x,int n)
{
int i; /* Variable used in loop counter */
int number = 1;
for (i = 0; i < n; ++i)
number *= x;
return(number);
}
#include <math.h>
printf ("%d", (int) pow (3, 4));
There's no operator for such usage in C, but a family of functions:
double pow (double base , double exponent);
float powf (float base , float exponent);
long double powl (long double base, long double exponent);
Note that the later two are only part of standard C since C99.
If you get a warning like:
"incompatible implicit declaration of built in function 'pow' "
That's because you forgot #include <math.h>.
For another approach, note that all the standard library functions work with floating point types. You can implement an integer type function like this:
unsigned power(unsigned base, unsigned degree)
{
unsigned result = 1;
unsigned term = base;
while (degree)
{
if (degree & 1)
result *= term;
term *= term;
degree = degree >> 1;
}
return result;
}
This effectively does repeated multiples, but cuts down on that a bit by using the bit representation. For low integer powers this is quite effective.
just use pow(a,b),which is exactly 3**4 in python
Actually in C, you don't have an power operator. You will need to manually run a loop to get the result. Even the exp function just operates in that way only. But if you need to use that function, include the following header
#include <math.h>
then you can use pow().

Multiplication of float with int in c

#include <stdio.h>
int main(){
float var = 0.612;
printf("%f\n",var);
printf("%f\n",var*100);
return 0;
}
o/p
0.612000
61.199997
I found that for JavaScript, we have .tofixed() method.
How do we get a fix for this in C?
You can specify the precision when printing:
printf("%.3f\n", 100 * var);
Since the exact number you're having probably isn't representable in the float itself, there is no operation you can do on the number itself to "remove" the decimals, it's all a matter of how you choose to present the data.

Resources