Random numbers double type - c++

I had an exercise in my book which made me to puzzle the answer by a long series of attempts which took me hours to configure out. I'm new to c++, and programming at all, which makes me lack of knowledge(actually I'm learning at home by the book). So i got a couple of questions which i hope you could answer them and "asset" my brains on the right place.
Before the questions, the exercise was :
"Write a random-number generator that returns a random floating point
number between 0.0 and 1.0. (Hint: Call rand, cast the result r to type
double by using static_cast(r), and then divide by the highest value
in the int range, RAND_MAX.) Make sure you declare the function with the
double return type.".
The questions:
what is the main function/idea that stands behind the srand(time(nullptr))?
I keep getting a warning of c4244 ('argument': conversion from 'time_t' to 'unsigned int'). I was searching the answer and I figured out the problem is in the srand command... please somebody can explain it?
I'm not truly clear about the static_cast and all the other 3 casting types . I know that in the static_cast i can define a new enum type from the parentheses to the braces from the left: static_cast<double>(r). But, what is the limit/definition of each cast(dynamic_cast, reinterpret_cast and const_cast)? When do i use them?
I figured out that i must declare a double before the (RAND_MAX) statement, but i have no idea why it must be double and not int or float? What is the main idea that stands behind the RAND_MAX?
This is the code that i wrote(note: I'm using #include "stdafx.h" pre header just in case of... while in the book there is nothing mentioned about it):
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
double rand_(int r);
int main() {
int n;
double r;
cout << " choose a number: ";
cin >> n;
srand(time(nullptr));
for (int i = 0; i <= n; i++) {
r = rand_(n) ;
cout << r << " ";
}
return 0;
}
double rand_(int r) {
static_cast<double>(r);
return rand() / double(RAND_MAX);
}
If you notice any "clearance" mistakes of basic coding please correct me.
Thanks for all who answer and support this post. Hope in future could do the same.

srand(time(nullptr));
its used to initialise pseudo random number generator, with seed, obtained from current time (to get different rundom numbers each time you run your ptogramm).
srand() accepts unisgned int parameter, time() return time_t, so here is your warning about conversion.
rand() / double(RAND_MAX)
rand() return integer value, RAND_MAX is integer constant, so to get floating point division, instead of integer division RAND_MAX is conversed to floating point type.
As for when to use which type of cast its bit to broad, and I'm pretty sure you can find info about every particular cast on SO or cppreference.

Related

pow() returning wrong result under specific conditions (and an unexpected fix) - Why is all this?

I have been creating a short program for implementing Sieve of Eratosthenes. In he program, I have used int startingPoint which held the value of the current prime number, which had it's multiplications being marked non-prime, starting from its square. I used the pow() function to calculate the square of the starting point in the current loop. While doing so, I came across a weird phenomenon. When startingPoint was equal to 5, then after int i = pow(startingPoint,2) the value of i was 24, instead of 25. This phenomenon occurred only when startingPoint was equal to 5. Afterwards, I ran a few tests, that leaded to the following code snippet:
#include <iostream>
#include <math.h>
int main()
{
int p=5;
int num1 = pow(5,2);
int num2 = pow(p,2);
float num3 = pow(p,2);
int num4 = floor(pow(p,2));
std::cout.precision(10);
std::cout<<num1<<std::endl; //25
std::cout<<num2<<std::endl; //24
std::cout<<std::fixed<<num3<<std::endl; //25.0000000000
std::cout<<num4<<std::endl; //25
}
As it can be seen, if I call pow with int literals, the result will be the actual square of the number. However, if I call it using int p=5, then what pow returns is actually one lower than the expected result. If I pass the result into a float variable, it also recieves the correct result.
Now, I know the way pow calculates powers is via approximation, and thus, errors such as this when converting to integer may occur. I might just let it be like that. But what REALLY made me stop and think is what happens with num4. pow(p,2) casted to int returns 24. But floor(pow(p,2)) casted to int returns 25. So the floor function, which, by standard rounds a number down, somehow makes the returned value cast into a higher integer value.
My question in short: Just how does that happen?
(I was using gcc 5.3.0 through MinGW)
Edit: As I already stated in the question, I can accept the reason behind pow return value being casted into a lower integer value, but what I really can't comprehend (and I haven't seen this being brought up anywhere else either) is how floor fixes that. How can floor make the return value of pow actually cast into a higher integer value? Now THAT is the real question.

Loss of precision while working with double

Could we work with big numbers up to 10^308.
How can I calculate the 11^105 using just double?
The answer of (11^105) is:
22193813979407164354224423199022080924541468040973950575246733562521125229836087036788826138225193142654907051
Is it possible to get the correct result of 11^105?
As I know double can handle 10^308 which is much bigger than 11^105.
I know that this code is wrong:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
double n, p, x;
cin >> n >> p;
//scanf("%lf %lf", &n,&p);
x = exp(log((double)n)*p);
//printf("%lf\n", x);
cout << x <<endl;
return 0;
}
Thanks.
double usually has 11bit for exp (-1022~1023 normalized), 52bit for fact and 1bit for sign. Thus 11^105 cannot be represented accurately.
For more explanation, see IEEE 754 on Wikipedia
Double can hold very large results, but not high precision. In constrast to fixed point numbers, double is floating point real number. This means, for the same accuracy double can shift the radix to handle different range of number and thus you see high range.
For your purpose, you need some home cooked big num library, or you can find one readily available and written by someone else.
BTW my home cooked recipe gives different answer for 11105
Confirmed with this haskell code

Why doesn't my C++ program calculate more digits of 'e'?

I recently picked up the c++ programming language, and I'm trying to calculate the digits of 'e' for a Calculus Project at school. I'll paste the pgoram that I've written below. It's based on e= lim(1+1/x)^x, as x-> infinity. In this program, I set x=100,000. I also set x=1,000,000 and noticed that the answers are somehow being subjected to a round-off error, instead of becoming longer in length.
Program:
#include <iostream>
#include <math.h>
using namespace std;
long double sum;
int main()
{
long double x=100000;
sum= (pow((1+(1/x)),(x)));
cout<<sum;
}
Any tips/ advice in making it print out more digits would be great. Thanks in advance.
On the first hand long double is limited in the number of digits it can produce, and because of how the real numbers are implemented it won't produce exact results.
But, to answer your question you can set cout's precision by doing
cout.precision(15);
cout << sum;
Also see this answer for more explanations and details see
How do I print a double value with full precision using cout?
Double in c++ is a floating point number. For accurate calculation like this you need use decimal number.
See this answer about decimal in cpp

Division in C++ not working as expected

I was working on something else, but everything came out as zero, so I made this minimalistic example, and the output is still 0.
#include <iostream>
int main(int argc, char** argv)
{
double f=3/5;
std::cout << f;
return 0;
}
What am I missing?
You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number:
double f = 3.0 / 5;
It doesn't need to be .0, you can also do 3./5 or 3/5. or 3e+0 / 5 or 3 / 5e-0 or 0xCp-2 / 5 or... There only needs to be an indicator involved so that the compiler knows it's supposed to perform the division as floating point.
Another possibility: double f=double(3)/5. That's much more typing, but it leaves no doubt to what you are doing.
Or simply use double f=.6, that also does the trick...
try this:
double f = 3.0/5.0;
this should fix your problem
Try putting a .0 after one of the divisors. This will convert them into floating point literals.
You are using integers. You can many things to make your constants double like leftaroundabout states, however that is not good clean good. It is hard to read and confusing. If you want 3 and 5 make them 3.0 and 5.0. Everyone will know what you mean if they are forced to read your code. Much of what he/she states really requires you to know C/C++ and how floats are storage to make heads or tails.
In case, you save your generic variables with int and would like to obtain the ratio as double:
using namespace std;
int main()
{
int x = 7;
int y = 4;
double ratio;
ratio = static_cast<double>(x)/static_cast<double>(y);
cout << "ratio =\t"<<ratio<< endl;
}

error: invalid operands to binary % (have 'double' and 'double')

I have a program I am writing that lists 100,000 prime numbers. It works fine for 10 numbers, but after so many numbers they turn into negative values. I changed the ints to long ints and that did not change anything, then I changed them to doubles and I get the error listed in the title. What should my variable be? Keep in mind I am still new to programing. I also looked at some previous posts and did not see the answer.
int is_prime(double x,char array[]){
//doesnt use array but I put it in there
double j=2;//divider
for(j=2;j<=pow(x,0.5);j++){
if((x%j==0)){
return(0);
} //isnt prime
}
return(1);// because it is prime.
}
You can't use a double with the operator, you must have an int.
You should: #include <math.h> and then use the fmod function.
if(fmod(x,j)==0)
Full code:
#include <math.h>
int is_prime(double x,char array[]){
//doesnt use array but I put it in there
double j=2;//divider
for(j=2;j<=pow(x,0.5);j++){
if(fmod(x,j)==0){
return(0);
} //isnt prime
}
return(1);// because it is prime.
}
You have two options:
Stick with the % operator, then you're required to cast the inputs to ints
if(((int)x % (int)j) == 0)
Include math.h and then use fmod:
if(fmod(x, j) == 0)
Your immediate question can be solved with fmod, but for your purpose of high-value prime numbers, you may be better off looking at a big-integer class, like that at http://sourceforge.net/projects/cpp-bigint/ since what you really want is integer mathematics, and using floats might cause problems as things progress.