介绍蒙特卡诺近似的例子代码
#include<fstream> #include<iostream> #include<cstdlib> #include<cstdio> #include<string> #include<ctime> #include<memory> using std::ifstream; using std::ofstream; using std::string; using std::cout; using std::endl; using std::ios; using std::unique_ptr; double randx() { return rand() % 100 / (double)99; } int main(void) { ifstream ifs("D:/tex.pbm"); string header; uint32_t w, h, l; ifs >> header; ifs >> w >> h >> l; cout << "w: " << w << " ,h: " << h << " ,l: " << l << endl; ifs.ignore(); unsigned char* pixles = new unsigned char[w * h * 3]; ifs.read((char*)pixles, w * h * 3); int nsamples = 8; srand(time(0)); float avgr = 0, avgg = 0, avgb = 0; float sumr = 0, sumg = 0, sumb = 0; for (int i = 0; i < nsamples; i++) { float x = randx() * w; float y = randx() * h; int n = ((int)(y * w) + int(x)) * 3; sumr += pixles[n]; sumg += pixles[n + 1]; sumb += pixles[n + 2]; } sumr /= nsamples; sumg /= nsamples; sumb /= nsamples; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int n = (i * w + j) * 3; avgr += pixles[n]; avgg += pixles[n + 1]; avgb += pixles[n + 2]; } } avgr /= w * h; avgg /= w * h; avgb /= w * h; printf("Average: %0.2f %0.2f %0.2f ", avgr, avgg, avgb); printf("Aproximation: %0.2f %0.2f %0.2f ", sumr, sumg, sumb); delete pixles; system("pause"); return 0; }