Rand generating equal numbers

Asked

Viewed 49 times

0

I have to do a program that generates random numbers for X1 and x2 and perform the operation F = X1*X1 + x2*x2; but I will repeat this 10 times and I will keep the lower value of F; then I will repeat 100 times and I will keep the lower value of F; and so on; The idea is that the program should have a tendency to show smaller and smaller values because of statistics However, my program is half-mocked, it is not showing smaller and smaller values, in fact it is showing a lot of repeated value Where I’m going wrong?

https://pastebin.com/zCx0EAtb

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

void FuncaoMenorValor(int z, int N, float* menoresF){ // z repersenta o tanto de vezes que a iteração do for vai rodar, N representa a posição do vetor menoresF que vai guardar o menor valor encontrado de F na iteração, e menoresF é o vetor que guarda os menores valores encontrados de F, de forma geral
float x1, x2, F = 0, menorF = 10;
int a, b, k, i;
    for(i = 0; i < z; i++){
        a = 1 + rand()%10; // dessa linha até a linha 24, é um algoritmo para gerar um numero no intervalo [-1,1]
        b = 1 + rand()%10;
        k = rand()%1;
        if(k == 0){
            x1 = (float) a/100;
        }
        if(k == 1){
            x1 = (float) -1*a/100;
        }
        k = rand()%1;
        if(k == 0){
            x2 = (float) b/100;
        }
        if(k == 1){
            x2 = (float) -1*b/100;
        }
        F = x1*x1+x2*x2;
        if(F < menorF){
            menorF = F;
        }
        if(i == (z-1)){ // quando o programa chega na ultima iteração, ele deve guardar o valor do menorF encontrado
            menoresF[N] = menorF;
        }
    }
}

int main(){

srand(time((NULL))); // seeda o rand

float menoresF[11];
int j;

FuncaoMenorValor(10, 0, menoresF);
FuncaoMenorValor(20, 1, menoresF);
FuncaoMenorValor(100, 2, menoresF);
FuncaoMenorValor(200, 3, menoresF);
FuncaoMenorValor(500, 4, menoresF);
FuncaoMenorValor(1000, 5, menoresF);
FuncaoMenorValor(2000, 6, menoresF);
FuncaoMenorValor(10000, 7, menoresF);
FuncaoMenorValor(20000, 8, menoresF);
FuncaoMenorValor(50000, 9, menoresF);
FuncaoMenorValor(100000, 10, menoresF);

for(j = 0; j < 11; j++){ // printa todos os valores do vetor menoresF
        printf("\n%f", menoresF[j]);
    }
return 0;
}
  • Post your code here, better than in external repositories. To make it code style, just start each line with 4 spaces. Or press ctrl+k in the code pasted here

  • How about changing the rand() % 1 for rand() % 2?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.