powerlaw.cpp

来自「模拟P2P各种网络环境的,适合新手们的学习,不错的源码.」· C++ 代码 · 共 44 行

CPP
44
字号
#include "PowerLaw.h"
#include "math.h"
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
static unsigned int myselect(double nums[], unsigned int numslen, double p){
	double probs[numslen];
	for( unsigned  int i =0; i< numslen; i++){
		if( nums[i] == 0)
			probs[i] = 0;
		else
			probs[i] = pow( nums[i], p);
	}

	double sum = 0;
	for( unsigned  int i = 0 ; i< numslen; i++)
		sum += probs[i];

	double r = sum *rand()/RAND_MAX;

	unsigned int i = 0;
	for( ; i< numslen; i++){
		r -= probs[i];
		if( r< 0)
			break;
	}
	return i;

}

unsigned int zipf( unsigned int size){
	double* nums = new double[size];
	for( unsigned int i =0; i< size; i++)
		nums[i] = i+1;
	return myselect(nums, size, -1.0);
}
/*
int main(){
	srand(time(NULL));
	for( int i = 0; i< 50; i++)
		printf("%d \n", zipf(20));
}
*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?