Answer the question
In order to leave comments, you need to log in
How to expand the range of random values from 0 to 1 inclusive?
Hello, gentlemen programmers, I was offered to solve such a problem - in the interval [0; 1] a and b are randomly selected, so that x^2 + a*x - 2*b = 0. The value k = max(x1,x2) . Find the probability that k > 1.
I have implemented a C program that finds this probability:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
using namespace std;
long double max(long double x1, long double x2)
{
return x1 > x2 ? x1 : x2;
}
int main()
{
setlocale(LC_ALL, "");
srand(time(NULL));
int n, count, N = 0;
long double a, b, discr, x1, x2;
cout << "Введите количество экспериментов:"; cin >> n;
for(int i = 1; i <= n; i++)
{
a = double(rand() % 1000000000000) / double(1000000000000);
b = double(rand() % 1000000000000) / double(1000000000000);
discr = a*a - 8*b;
x1 = (-a + pow(discr, 1.0/2.0))/2.0;
x2 = (-a - pow(discr, 1.0/2.0))/2.0;
if(discr < 0)
continue;
else if( max(x1,x2) > 1 )
{
cout << "При a = " << a << " и b = " << b << " x1 = " << x1 << " x2 = " << x2 << " max = " << max(x1,x2) << endl;
++count;
}
}
printf("\nP(A) = %.10f", float(count) / float(n));
return 0;
}
Answer the question
In order to leave comments, you need to log in
To begin with, it is worth checking whether there are any x values \u200b\u200bthat are greater than one.
D = a 2 + 8×b, D ∈ [0, 9]
x 1 = (−a + √D) / 2, x 1 ∈ [-1, √2]
x 2 = (−a − √D) / 2, x 1 ∈ [-2, 0]
There are required values. And they are achieved only at one of the roots. So it makes sense to write a program and determine the probability using the Monte Carlo method.
const monteCarlo = (tryCount) => {
let positive = 0;
for (let i = 0; i < tryCount; i += 1) {
const a = Math.random();
const b = Math.random();
const D = a * a + 8 * b;
const x = (-a + Math.sqrt(D)) / 2;
if (x > 1) {
positive += 1;
}
}
return(positive / tryCount);
}
monteCarlo(1000000); // 0.249374
monteCarlo(10000000); // 0.2500279
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question