pcg_basic.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. /*
  5. * PCG Random Number Generation for C.
  6. *
  7. * Copyright 2014 Melissa O'Neill <oneill@pcg-random.org>
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. *
  21. * For additional information about the PCG random number generation scheme,
  22. * including its license and other licensing options, visit
  23. *
  24. * http://www.pcg-random.org
  25. */
  26. #include "pcg_basic.h"
  27. void pcg32_srandom_r(pcg32_random_t* rng, uint64_t initial_state, uint64_t initseq) {
  28. rng->state = 0U;
  29. rng->inc = (initseq << 1u) | 1u;
  30. pcg32_random_r(rng);
  31. rng->state += initial_state;
  32. pcg32_random_r(rng);
  33. }
  34. uint32_t pcg32_random_r(pcg32_random_t* rng) {
  35. uint64_t oldstate = rng->state;
  36. rng->state = oldstate * 6364136223846793005ULL + rng->inc;
  37. uint32_t xorshifted = (uint32_t)(((oldstate >> 18u) ^ oldstate) >> 27u);
  38. uint32_t rot = (uint32_t)(oldstate >> 59u);
  39. return (xorshifted >> rot) | (xorshifted << ((~rot + 1u) & 31)); /* was (xorshifted >> rot) | (xorshifted << ((-rot) & 31)) */
  40. }