void stress_test() { boost::posix_time::time_duration d; { std::vector<int> v; for(int i = 0; i < 4000000; ++i) v.push_back(i); boost::posix_time::ptime t1=boost::posix_time::microsec_clock::local_time(); tpie::parallel_sort_impl<std::vector<int>::iterator, std::less<int>, 42> s(0); s(v.begin(), v.end()); boost::posix_time::ptime t2=boost::posix_time::microsec_clock::local_time(); d=t2-t1; } boost::rand48 prng(42); while(true) { size_t size = (1 << (prng()%18)) + prng()%100; std::vector<int> v1; std::vector<int> v2; for (size_t i=0; i < size; ++i) { v1.push_back(prng()); v2.push_back(v1.back()); } std::cout << size << " "; boost::posix_time::ptime t1=boost::posix_time::microsec_clock::local_time(); std::sort(v1.begin(), v1.end()); boost::posix_time::ptime t2=boost::posix_time::microsec_clock::local_time(); tpie::parallel_sort_impl<std::vector<int>::iterator, std::less<int>, 42> s(0); s(v2.begin(), v2.end()); boost::posix_time::ptime t3=boost::posix_time::microsec_clock::local_time(); if(v1 != v2) {std::cerr << "Failed" << std::endl; return;} std::cout << "std: " << (t2-t1) << " ours: " << t3-t2 << std::endl; if( std::max(d,(t2-t1)*3) < (t3-t2) ) {std::cerr << "Too slow" << std::endl; return;} } }
void ateach_scattered( size_t seed, size_t x_scale, size_t y_scale, int x_strength, int y_strength, ptrdiff_t x_min, ptrdiff_t x_max, ptrdiff_t y_min, ptrdiff_t y_max, void *arg, void (*f)(int, int, void *) ) { int x, y; int xi = 0, yi = 0; // grid indices for (xi = x_min/x_scale; xi <= x_max/x_scale; xi += 1) { for (yi = y_min/y_scale; yi <= y_max/y_scale; yi += 1) { x = xi*x_scale; x += (prng(seed*xi + xi + yi)) % (2*x_strength) - x_strength; y = yi*y_scale; y += (prng(seed*yi + xi - yi)) % (2*y_strength) - y_strength; if (x >= x_min && x < x_max && y >= x_min && y < y_max) { f(x, y, arg); } } } }
// Common random decisions and setup for herb leaves/stems: hash setup, // nstalks, and spread. static inline void herb_setup( herb_leaves_filter_args *hlfargs, ptrdiff_t *hash, float *noise, int *nstalks, float *spread, leaf_filter_args *lfargs ) { *hash = prng(hlfargs->seed); *noise = 0.7 + 0.6 * ptrf(*hash); // [0.7, 1.3] *hash = prng(*hash); *nstalks = (int) (hlfargs->count * (*noise) + 0.5); if (*nstalks < 1) { *nstalks = 1; } *noise = 0.75 + 0.5 * ptrf(*hash); // [0.75, 1.25] *hash = prng(*hash); *spread = hlfargs->spread * (*noise); if (*spread > MAX_BULB_SPREAD) { *spread = MAX_BULB_SPREAD; } *spread *= BLOCK_TEXTURE_SIZE / 2.0; lfargs->main_color = hlfargs->main_color; lfargs->vein_color = hlfargs->vein_color; lfargs->dark_color = hlfargs->dark_color; lfargs->bend = hlfargs->bend; lfargs->length = hlfargs->length; lfargs->width = hlfargs->width; lfargs->stem_length = 0; // shape is set differently for leaves/stems }
void rustle_sheet( tectonic_sheet *ts, float strength, float scale, ptrdiff_t seed ) { int i, j, idx; vector *p; ptrdiff_t oseed; seed = prng(seed + 71); oseed = prng(seed + 30); for (i = 0; i < sheet_pwidth(ts); ++i) { for (j = 0; j < sheet_pheight(ts); ++j) { idx = sheet_pidx(ts, i, j); p = &(ts->points[idx]); p->x += strength * sxnoise_2d( p->x * scale, p->y * scale, seed ); p->y += strength * sxnoise_2d( p->x * scale, p->y * scale, oseed ); } } }
static MatrixPtrType apply(int n, int seed=-1) { /** 0. If there is no good seed given, use a good random seed */ if (0>seed) seed = detail::generate_seed(); /** 1. Generate a uniformly random ([0,1]) matrix A */ /** * Note: There is a random function (MatrixXd::Random(m,n), but I don't * know what kind of random numbers they are using. So, we will use * boost::random to fill in the entries. Change it later when we * understand * Random() better. */ uni_real_prng_type prng ((engine_type(seed)), (uni_real_type())); MatrixPtrType A = MatrixPtrType(new MatrixType(n,n)); for (int j=0; j<n; ++j) { for (int i=0; i<n; ++i) { A->operator()(i,j) = prng(); } } MatrixPtrType A_trans = MatrixPtrType(new MatrixType(A->transpose())); /** 2. Compute A = A+A^T, which makes A symmetric */ (*A) += (*A_trans); /** 3. As A(i,j) is originally (0,1), we can add n*I to make it PSD */ for (int i=0; i<A->rows(); ++i) A->operator()(i,i) += n; return A; }
species create_new_herb_species(ptrdiff_t seed) { species result = create_herb_species(); herb_species* hsp = get_herb_species(result); determine_new_plant_materials(&(hsp->materials), seed); seed = prng(seed); determine_new_herb_appearance(&(hsp->appearance), seed); seed = prng(seed); hsp->growth.seed_growth.grammar = BIO_CG_SPROUT_IN_SOIL; hsp->growth.seed_growth.sprout_time = ( posmod(prng(seed + 1771), 5) + posmod(prng(seed + 311), 8) ); seed = prng(seed); // TODO: Real values here... hsp->growth.seed_growth_resist = 5; hsp->growth.growth_resist = 10; hsp->growth.growth_strength = 8; determine_new_herb_core_growth(&(hsp->growth.core_growth), seed); return result; }
void add_continents_to_sheet( tectonic_sheet *ts, float strength, float scale, float dstr, float dscale, ptrdiff_t seed ) { size_t i, j, idx; size_t pw, ph; float fx, fy; vector *p; ptrdiff_t dxseed, dyseed; float xphase, yphase; dxseed = prng(seed); dyseed = prng(dxseed); seed = prng(seed + 18291); xphase = ptrf(seed); seed = prng(seed + 6546); yphase = ptrf(seed); pw = sheet_pwidth(ts); ph = sheet_pwidth(ts); // Only pass: add continent height for (i = 0; i < pw; ++i) { for (j = 0; j < ph; ++j) { idx = sheet_pidx(ts, i, j); p = &(ts->points[idx]); fx = p->x; fy = p->y; // distortion fx += dstr * sxnoise_2d( p->x * dscale, p->y * dscale, dxseed ); fy += dstr * sxnoise_2d( p->x * dscale, p->y * dscale, dyseed ); // scaling: fx *= scale; fy *= scale; // sin/cos continents: p->z += strength * ( sin(2.0 * M_PI * (fx + xphase)) * cos(2.0 * M_PI * (fy + yphase)) ); } } }
static SparseMatrixPtrType apply(int n, int nnz, int seed=-1) { /** If there is no good seed given, use a good random seed */ if (0>seed) seed = detail::generate_seed(); /** 0. Generate the dense matrix */ DenseMatrixPtrType A_dense = rand_psd_t<DenseMatrixType>::apply(n, seed); /** * 1. We will generate a sparse matrix in the following way: * - Leave the diagonal as is --- this takes care of n entries. So we * have * (n-nnz) non-zero entries left. This means that we have * n*n-n+nnz entries to zero out. * - Since we are dealing with symmetric matrices, exactly half of these * entries should be in the UPPER triangle and then we can simply reflect * everything about the diagonal. * - Go through each element in the UPPER triangle and choose to keep it * with a probability of (nnz)/(n*n-n). * * Caveat: * All this assumes the following: (nnz>n and nnz<(n*n)) */ if (nnz<n) { /** error */ } else if (nnz>(n*n)) { /** error */ } const double p = static_cast<double>(nnz-n) / static_cast<double>((n*n) - n); int true_nnz = n; bernoulli_real_prng_type prng ((engine_type(seed)), (bernoulli_real_type(p))); std::vector<TripletType> nnz_entries; for (int j=0; j<n; ++j) { for (int i=j; i<n; ++i) { if (i==j) nnz_entries.push_back (TripletType(i,j,A_dense->operator()(i,j))); else if (prng()) { nnz_entries.push_back(TripletType(i,j,A_dense->operator()(i,j))); nnz_entries.push_back(TripletType(j,i,A_dense->operator()(i,j))); ++true_nnz; ++true_nnz; } else { /** zeroed out */ } } } /** * Now, simply create the SparseMatrix that we need from this DenseMatrix */ SparseMatrixPtrType A(new SparseMatrixType(n,n)); A->setFromTriplets(nnz_entries.begin(), nnz_entries.end()); A->makeCompressed(); return A; }
void fltr_leaves_helper(int x, int y, void * arg) { struct leaves_helper_args_s *lhargs = (struct leaves_helper_args_s *) arg; // Scramble the leaf filter seed: lhargs->lfargs->seed = prng(prng(lhargs->lfargs->seed + x) * y); // Render a single randomized leaf into the leaf texture: fltr_leaf(lhargs->leaf, lhargs->lfargs); // Draw the fresh leaf onto the main texture at the given position: tx_draw_wrapped(lhargs->tx, lhargs->leaf, x, y); }
uint8_t Chargen(unsigned char *Data, uint8_t DataLen, unsigned char *Response, uint8_t *ResponseLen) { uint8_t NumBytes; uint8_t i; NumBytes = prng() % 127; for (i = 0; i < NumBytes; i++) { Response[i] = prng() % 256; } *ResponseLen = NumBytes; return(1); }
void fltr_herb_stems(texture *tx, void const * const fargs) { herb_leaves_filter_args *hlfargs = (herb_leaves_filter_args *) fargs; ptrdiff_t hash; int i = 0; float noise; int nstalks; float spread; leaf_filter_args lfargs; // stores individual leaf parameters curve c; // stores individual leaf shapes c.from.y = BLOCK_TEXTURE_SIZE; c.to.y = 0; c.from.z = 0; c.come_from.z = 0; c.go_towards.z = 0; c.to.z = 0; herb_setup(hlfargs, &hash, &noise, &nstalks, &spread, &lfargs); lfargs.shape = LS_LINEAR; float th_base = 0; float mid = (BLOCK_TEXTURE_SIZE / 2); for (i = 0; i < nstalks; ++i) { // generate x in [mid - spread, mid + spread] // for stems, we use the same top/bottom values so that they'll fit // together vertically. c.from.x = mid - spread; c.from.x += 2 * spread * ptrf(hash + i); c.to.x = c.from.x; hash = prng(hash + i + c.from.x); // pick the same starting angle that leaves use [-1, 1] noise = 1.0 - 2 * ptrf(hash); hash = prng(hash + i); th_base = hlfargs->angle * noise; // An extra hash to maintain stride with fltr_herb_leaves: hash = prng(hash + i); // stems use the same angle at the top and bottom so that they can stack. c.come_from.x = c.to.x - sinf(th_base) * hlfargs->length*hlfargs->shape; c.come_from.y = c.to.y + cosf(th_base) * hlfargs->length*hlfargs->shape; c.go_towards.x = c.from.x + sinf(th_base) * hlfargs->length*hlfargs->shape; c.go_towards.y = c.from.y - cosf(th_base) * hlfargs->length*hlfargs->shape; // pick a base width in [0.75, 1.25] noise = 0.75 + 0.5 * ptrf(hash); hash = prng(hash + i); lfargs.width = hlfargs->width * noise; // draw the leaf: draw_leaf(tx, &c, &lfargs); } }
hasher make_hasher(size_t k, size_t seed, bool double_hashing) { assert(k > 0); std::minstd_rand0 prng(seed); if (double_hashing) { auto h1 = default_hash_function(prng()); auto h2 = default_hash_function(prng()); return double_hasher(k, std::move(h1), std::move(h2)); } else { std::vector<hash_function> fns(k); for (size_t i = 0; i < k; ++i) fns[i] = default_hash_function(prng()); return default_hasher(std::move(fns)); } }
bool basic1() { boost::rand48 prng(42); std::vector<int> v1; std::vector<int> v2; for (size_t i=0; i < 1234567; ++i) { int x = prng(); v1.push_back(x); v2.push_back(x); } std::sort(v1.begin(), v1.end()); tpie::parallel_sort_impl<std::vector<int>::iterator, std::less<int>, 42> s(0); s(v2.begin(), v2.end()); if(v1 != v2) {std::cerr << "Failed" << std::endl; return false;} return true; }
TEST_F(RangeTest, testRangeTree) { NumericRangeTree *t = NewNumericRangeTree(); ASSERT_TRUE(t != NULL); for (size_t i = 0; i < 50000; i++) { NumericRangeTree_Add(t, i + 1, (double)(1 + prng() % 5000)); } ASSERT_EQ(t->numRanges, 16); ASSERT_EQ(t->numEntries, 50000); struct { double min; double max; } rngs[] = {{0, 100}, {10, 1000}, {2500, 3500}, {0, 5000}, {4999, 4999}, {0, 0}}; for (int r = 0; rngs[r].min || rngs[r].max; r++) { Vector *v = NumericRangeTree_Find(t, rngs[r].min, rngs[r].max); ASSERT_TRUE(Vector_Size(v) > 0); // printf("Got %d ranges for %f..%f...\n", Vector_Size(v), rngs[r].min, rngs[r].max); for (int i = 0; i < Vector_Size(v); i++) { NumericRange *l; Vector_Get(v, i, &l); ASSERT_TRUE(l); // printf("%f...%f\n", l->minVal, l->maxVal); ASSERT_FALSE(l->minVal > rngs[r].max); ASSERT_FALSE(l->maxVal < rngs[r].min); } Vector_Free(v); } NumericRangeTree_Free(t); }
// static void GPolynomial::test() { GPolynomialSingleLabel::test(); GRand prng(0); GPolynomial poly(prng); poly.basicTest(0.78, -1.0/*skip it*/); }
/* Encrypt or Decrypt */ void rc4(u_char *key, u_char *input, u_char *output, int keylen, int msglen) { int i; u_char State[256]; u_char *keystream; initialize(State); ksa(State, key, keylen); printf("\n--- Tamaño del mensaje %d\n", msglen); keystream = prng(State, msglen); for(i=0; i<msglen; i++) output[i] = input[i] ^ keystream[i]; printf("\n--- Key Generation ---\nKey: %s\n\n", key); printf("Keystream:\n"); for(i=0; i<msglen; i++) { if(i%16==0) { printf("\n"); printf("%d:\t", i); } if(keystream[i]<16) printf("0%x ", keystream[i]); else printf("%x ", keystream[i]); } }
// static void GLinearRegressor::test() { GRand prng(0); GLinearRegressor_linear_test(prng); GAutoFilter af(new GLinearRegressor ()); af.basicTest(0.76, 0.93); }
cg_expansion* pick_expansion( cell_grammar *cg, chunk_neighborhood* nbh, block_index base, ptrdiff_t seed ) { size_t i; int success; cg_expansion *exp; list *options = create_list(); block root_block = *nb_block(nbh, base); for (i = 0; i < l_get_length(cg->expansions); ++i) { exp = (cg_expansion*) l_get_item(cg->expansions, i); success = check_expansion(exp, nbh, base, root_block); if (success) { l_append_element(options, (void*) exp); } } if (l_is_empty(options)) { cleanup_list(options); return NULL; } // Choose an option based on our seed: i = posmod(prng(seed + 819991), l_get_length(options)); exp = (cg_expansion*) l_get_item(options, i); cleanup_list(options); return exp; }
int main() { actor<int> main_actor{[] (decltype(main_actor)& self) { actor<std::string> logger_actor{[] (decltype(logger_actor)& self) { for (;;) { auto message = self.receive(); std::cout << self.receive() << '\n'; } }}; actor<std::tuple<actor<int>*, int, int>> random_number_generator_actor{[] (decltype(random_number_generator_actor)& self) { std::mt19937 prng(std::time(nullptr)); for (;;) { auto message = self.receive(); std::uniform_int_distribution<> dis(std::get<1>(message), std::get<2>(message)); std::get<0>(message)->send(dis(prng)); } }}; for (int i = 0; i < 10; ++i) { random_number_generator_actor.send(std::make_tuple(&self, 0, 10)); int x = self.receive(); logger_actor.send(std::to_string(x)); } }}; }
/*---------------------------------------------------------------------------*/ void ecc_gen_private_key(NN_DIGIT *PrivateKey) { NN_UINT order_digit_len; NN_UINT order_bit_len; char done = FALSE; uint8_t ri; NN_DIGIT digit_mask; order_bit_len = NN_Bits(param.r, NUMWORDS); order_digit_len = NN_Digits(param.r, NUMWORDS); while (!done) { prng((uint8_t *)PrivateKey, order_digit_len * sizeof(NN_Digits)); for (ri = order_digit_len; ri < NUMWORDS; ri++) { PrivateKey[ri] = 0; } if (order_bit_len % NN_DIGIT_BITS != 0) { digit_mask = MAX_NN_DIGIT >> (NN_DIGIT_BITS - order_bit_len % NN_DIGIT_BITS); PrivateKey[order_digit_len - 1] = PrivateKey[order_digit_len - 1] & digit_mask; } NN_ModSmall(PrivateKey, param.r, NUMWORDS); if (NN_Zero(PrivateKey, NUMWORDS) != 1) { done = TRUE; } }
void GPriorityQueue::test() { int* buf = new int[TEST_SIZE]; std::unique_ptr<int[]> hBuf(buf); int i, t, r; for(i = 0; i < TEST_SIZE; i++) buf[i] = i; GRand prng(0); for(i = TEST_SIZE; i > 2; i--) { r = (int)prng.next(i); t = buf[r]; buf[r] = buf[i - 1]; buf[i - 1] = t; } GPriorityQueue q(GPriorityQueueTestComparer, NULL); for(i = 0; i < TEST_SIZE; i++) q.insert(buf + i); int* pInt; for(i = 0; i < (TEST_SIZE / 2); i++) { pInt = (int*)q.minimum(); q.removeMin(); if(*pInt != i) throw Ex("wrong answer"); pInt = (int*)q.maximum(); q.removeMax(); if(*pInt != (TEST_SIZE - 1) - i) throw Ex("wrong answer"); } }
/** * Test that nextCanonicalDouble() always returns values between 0 and 1. */ TEST(RandomTest, NextCanonicalWithinRange) { PseudoRandom prng(10); for (int i = 0; i < 100; i++) { double next = prng.nextCanonicalDouble(); ASSERT_LTE(0.0, next); ASSERT_LT(next, 1.0); } }
/* * NAME: dither() * DESCRIPTION: dither and scale sample */ static __inline signed int dither(mad_fixed_t sample, struct dither *dither) { unsigned int scalebits; mad_fixed_t output, mask, random; enum { MIN = -MAD_F_ONE, MAX = MAD_F_ONE - 1 }; /* noise shape */ sample += dither->error[0] - dither->error[1] + dither->error[2]; dither->error[2] = dither->error[1]; dither->error[1] = dither->error[0] / 2; /* bias */ output = sample + (1L << (MAD_F_FRACBITS + 1 - SAMPLE_DEPTH - 1)); scalebits = MAD_F_FRACBITS + 1 - SAMPLE_DEPTH; mask = (1L << scalebits) - 1; /* dither */ random = prng(dither->random); output += (random & mask) - (dither->random & mask); dither->random = random; /* clip */ if (output > MAX) { output = MAX; if (sample > MAX) sample = MAX; } else if (output < MIN) { output = MIN; if (sample < MIN) sample = MIN; } /* quantize */ output &= ~mask; /* error feedback */ dither->error[0] = sample - output; /* scale */ return output >> scalebits; }
/** * \brief Performs setup and re-initialization needed before each new game. * * Resets the player score, resets variables for drawing columns, sets a new random ghost color, moves the player back to the starting position, erases columns from last game, * turns scrolling back on and makes the player visible again. */ static void gameSetup() { randomSky(); //fill screen with tile 1 again to erase menu ClearVram(); for(u8 i = 0; i < 4; i++) //reset column data with 0's to start fresh { pipe_x[i] = 0; pipe_y[i] = 0; } for(u8 k = 0; k < 32; k++) { bg[k] = 1; } //reset all score data from last game to 0 score = 0;//score = 0; score_ones=0; score_tens=0; score_hundreds=0; fake_x = 80; //reset how far we've flown player_x = 80; //reset player position player_y = 40; yspeed = 0; //make sure we start at 0 speed //draw the background for(u8 i = 0; i < VRAM_TILES_H; i++) { pipe_alarm=2; //make sure we never draw a column while we're drawing the starting screen loadNextStripe(); //go through each column and draw the background } //select a random color for the ghost and set the appropriate sprite ghost_color=(prng()%3); //the ghost has 3 frames and 3 color options, so we set the active sprite to the frame count (0 - 2) + the color (0, 3, or 6) to get the correct sprite ghost_color=(ghost_color+(ghost_color<<1)); current_sprite = player_sprites[current_frame+ghost_color]; //assign and move the player image to start the new game MoveSprite(0,player_x,player_y,3,3); MapSprite2(0,current_sprite,0); //make player visible SetSpriteVisibility(true); //reset variables to draw new columns correctly current_pipe=0; build_pipe=0; pipe_alarm = 1; pipe_col_drawn = 0; //turn scrolling on to begin the game scrollingOn=true; }
frequent_species pick_appropriate_frequent_species( list *sp_list, block substrate, ptrdiff_t seed ) { float weight; float total_weight = 0; float choice; float rare_smoothing; size_t i; frequent_species fqsp = 0; list *weights = create_list(); if (l_is_empty(sp_list)) { // Return an invalid species... frequent_species_set_species_type(&fqsp, SPT_NO_SPECIES); frequent_species_set_species(&fqsp, SP_INVALID); frequent_species_set_frequency(&fqsp, 0.0); return fqsp; } rare_smoothing = expdist(ptrf(seed + 31376), BIO_RARE_SPECIES_SMOOTHING_EXP); rare_smoothing *= BIO_RARE_SPECIES_SMOOTHING_ADJUST; for (i = 0; i < l_get_length(sp_list); ++i) { fqsp = (frequent_species) l_get_item(sp_list, i); weight = ( species_compatability(fqsp, substrate) * frequent_species_frequency(fqsp) ) + rare_smoothing; l_append_element(weights, f_as_p(weight)); total_weight += weight; } choice = ptrf(prng(seed + 866859)) * total_weight; for (i = 0; i < l_get_length(sp_list); ++i) { fqsp = (frequent_species) l_get_item(sp_list, i); choice -= p_as_f(l_get_item(weights, i)); if (choice < 0) { cleanup_list(weights); return fqsp; } } cleanup_list(weights); #ifdef DEBUG printf("Error: Ran out of appropriate species to pick from!\n"); exit(EXIT_FAILURE); #endif // Just arbitrarily return the first item (this shouldn't be reachable): return (frequent_species) l_get_item(sp_list, 0); }
int main(int argc, char** argv) { printf("%d arguments\n", argc); for (int idx = 0; idx < argc; idx++) { printf("Argument %d: %s\n", idx, argv[idx]); } const size_t num_points = (argc >= 2) ? (size_t)(atoi(argv[1])) : 1000; std::cout << "Generating " << num_points << " random points..." << std::endl; const auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); std::mt19937_64 prng(seed); std::uniform_real_distribution<double> dist(0.0, 10.0); EigenHelpers::VectorVector3d random_points(num_points); std::vector<size_t> indices(num_points); for (size_t idx = 0; idx < num_points; idx++) { const double x = dist(prng); const double y = dist(prng); random_points[idx] = Eigen::Vector3d(x, y, 0.0); indices[idx] = idx; } std::cout << "Clustering " << num_points << " points..." << std::endl; std::function<double(const Eigen::Vector3d&, const Eigen::Vector3d&)> distance_fn = [] (const Eigen::Vector3d& v1, const Eigen::Vector3d& v2) { return EigenHelpers::Distance(v1, v2); }; const Eigen::MatrixXd distance_matrix = arc_helpers::BuildDistanceMatrixParallel(random_points, distance_fn); const std::vector<std::vector<size_t>> clusters = simple_hierarchical_clustering::SimpleHierarchicalClustering::Cluster(indices, distance_matrix, 1.0, simple_hierarchical_clustering::COMPLETE_LINK).first; for (size_t cluster_idx = 0; cluster_idx < clusters.size(); cluster_idx++) { const std::vector<size_t>& current_cluster = clusters[cluster_idx]; const double cluster_num = 1.0 + (double)cluster_idx; for (size_t element_idx = 0; element_idx < current_cluster.size(); element_idx++) { const size_t index = current_cluster[element_idx]; random_points[index].z() = cluster_num; } } std::cout << "Saving to CSV..." << std::endl; const std::string log_file_name = (argc >=3 ) ? std::string(argv[2]) : "/tmp/test_hierarchical_clustering.csv"; std::ofstream log_file(log_file_name, std::ios_base::out); if (!log_file.is_open()) { std::cerr << "\x1b[31;1m Unable to create folder/file to log to: " << log_file_name << "\x1b[0m \n"; throw std::invalid_argument("Log filename must be write-openable"); } for (size_t idx = 0; idx < num_points; idx++) { const Eigen::Vector3d& point = random_points[idx]; log_file << point.x() << "," << point.y() << "," << point.z() << std::endl; } log_file.close(); std::cout << "Done saving, you can import into matlab and draw with \"scatter3(x, y, z, 50, z, '.')\"" << std::endl; return 0; }
coap_pdu_t* CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *options, const char* payload) { OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload"); coap_pdu_t *pdu; coap_list_t *opt; unsigned char _token_data[8]; str the_token = { 0, _token_data }; if (!(pdu = coap_new_pdu())) return NULL; /* initialize message id */ unsigned short message_id; prng((unsigned char *)&message_id, sizeof(unsigned short)); pdu->hdr->type = msgtype; pdu->hdr->id = htons(++message_id); pdu->hdr->code = code; pdu->hdr->token_length = the_token.length; if (!coap_add_token(pdu, the_token.length, the_token.s)) { OIC_LOG(DEBUG, TAG,"cannot add token to request"); } for (opt = options; opt; opt = opt->next) { coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *)opt->data), COAP_OPTION_LENGTH(*(coap_option *)opt->data), COAP_OPTION_DATA(*(coap_option *)opt->data)); } if (NULL != payload) { uint32_t len = strlen(payload); if ((flags & CA_FLAGS_BLOCK) == 0) { OIC_LOG_V(DEBUG, TAG, "coap_add_data, payload: %s", payload); coap_add_data(pdu, len, payload); } else { OIC_LOG_V(DEBUG, TAG, "coap_add_block, payload: %s", payload); coap_add_block(pdu, len, payload, block.num, block.szx); } } return pdu; }
static FLaC__INLINE FLAC__int32 linear_dither(unsigned source_bps, unsigned target_bps, FLAC__int32 sample, dither_state *dither, const FLAC__int32 MIN, const FLAC__int32 MAX) { unsigned scalebits; FLAC__int32 output, mask, random; FLAC__ASSERT(source_bps < 32); FLAC__ASSERT(target_bps <= 24); FLAC__ASSERT(target_bps <= source_bps); /* noise shape */ sample += dither->error[0] - dither->error[1] + dither->error[2]; dither->error[2] = dither->error[1]; dither->error[1] = dither->error[0] / 2; /* bias */ output = sample + (1L << (source_bps - target_bps - 1)); scalebits = source_bps - target_bps; mask = (1L << scalebits) - 1; /* dither */ random = (FLAC__int32)prng(dither->random); output += (random & mask) - (dither->random & mask); dither->random = random; /* clip */ if(output > MAX) { output = MAX; if(sample > MAX) sample = MAX; } else if(output < MIN) { output = MIN; if(sample < MIN) sample = MIN; } /* quantize */ output &= ~mask; /* error feedback */ dither->error[0] = sample - output; /* scale */ return output >> scalebits; }
/* code from madplay */ static inline signed int dither( mad_fixed_t sample, audio_dither *dither ) { unsigned int scalebits; mad_fixed_t output, mask, random; enum { MIN = -MAD_F_ONE, MAX = MAD_F_ONE - 1 }; /* noise shape */ sample += dither->error[0] - dither->error[1] + dither->error[2]; dither->error[2] = dither->error[1]; dither->error[1] = dither->error[0] / 2; /* bias */ output = sample + (1L << (MAD_F_FRACBITS + 1 - 16 - 1)); scalebits = MAD_F_FRACBITS + 1 - 16; mask = (1L << scalebits) - 1; /* dither */ random = prng(dither->random); output += (random & mask) - (dither->random & mask); dither->random = random; /* clip */ /* TODO: better clipping function */ if (sample >= MAD_F_ONE) sample = MAD_F_ONE - 1; else if (sample < -MAD_F_ONE) sample = -MAD_F_ONE; if (output >= MAD_F_ONE) output = MAD_F_ONE - 1; else if (output < -MAD_F_ONE) output = -MAD_F_ONE; /* quantize */ output &= ~mask; /* error feedback */ dither->error[0] = sample - output; /* scale */ return output >> scalebits; }
// Generate an unsigned integer in the range min to max, inclusive. uint32_t random_in_range(uint32_t min, uint32_t max) { if (max <= min) { return 0; } unsigned int range = max - min + 1; unsigned int scale_factor = 0xffffffff / range; unsigned int rand_uint; do { rand_uint = prng(); } while (rand_uint >= scale_factor * range); // Discard numbers that would cause bias return (rand_uint / scale_factor + min); }