When I call calc(), he doesnt give me the first return value for x, intstead he jumps back to double x = v1*sqrt((-(2.0*log(s)))/s);
and calculates the x for a second time and returns nan.
The debugger shows me, before he tries to return x for the first time, that the value of x is -0.525209. I thought that would be an acceptable return value (double).
Does anyone know how to solve this or why he jumps back? (sorry I'm still a beginner at c++)
#include <cmath>
#include <cstdlib>
#include <iostream>
double calc(){
double u1 = static_cast <double> (rand()) / static_cast <double> (RAND_MAX);
double u2 = static_cast <double> (rand()) / static_cast <double> (RAND_MAX);
double v1 = (2.0*u1)-1.0;
double v2 = (2.0*u2)-1.0;
double s = pow(v1, 2.0)+pow(v2, 2.0);
if (s >= 1.0){
calc();
}
double x = v1*sqrt((-(2.0*log(s)))/s);
std::cout << "before return " << x << std::endl;
return x;
}
int main(){
double hilfe = calc();
std::cout << "my mumber "<< hilfe << std::endl;
}
I guess you want this:
#include <cmath>
#include <cstdlib>
#include <iostream>
double calc(){
for (;;) {
double u1 = static_cast <double> (rand()) / static_cast <double> (RAND_MAX);
double u2 = static_cast <double> (rand()) / static_cast <double> (RAND_MAX);
double v1 = (2.0*u1)-1.0;
double v2 = (2.0*u2)-1.0;
double s = pow(v1, 2.0)+pow(v2, 2.0);
if (s >= 1.0)
continue;
double x = v1*sqrt((-(2.0*log(s)))/s);
std::cout << "before return " << x << std::endl;
return x;
}
}
int main(){
double hilfe = calc();
std::cout << "my mumber "<< hilfe << std::endl;
}
This picks new random values until s < 1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.