laplace.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #include "orconfig.h"
  6. #include "lib/math/laplace.h"
  7. #include "lib/math/fp.h"
  8. #include "lib/log/util_bug.h"
  9. #include <math.h>
  10. #include <stdlib.h>
  11. /** Transform a random value <b>p</b> from the uniform distribution in
  12. * [0.0, 1.0[ into a Laplace distributed value with location parameter
  13. * <b>mu</b> and scale parameter <b>b</b>. Truncate the final result
  14. * to be an integer in [INT64_MIN, INT64_MAX]. */
  15. int64_t
  16. sample_laplace_distribution(double mu, double b, double p)
  17. {
  18. double result;
  19. tor_assert(p >= 0.0 && p < 1.0);
  20. /* This is the "inverse cumulative distribution function" from:
  21. * http://en.wikipedia.org/wiki/Laplace_distribution */
  22. if (p <= 0.0) {
  23. /* Avoid taking log(0.0) == -INFINITY, as some processors or compiler
  24. * options can cause the program to trap. */
  25. return INT64_MIN;
  26. }
  27. result = mu - b * (p > 0.5 ? 1.0 : -1.0)
  28. * tor_mathlog(1.0 - 2.0 * fabs(p - 0.5));
  29. return clamp_double_to_int64(result);
  30. }
  31. /** Add random noise between INT64_MIN and INT64_MAX coming from a Laplace
  32. * distribution with mu = 0 and b = <b>delta_f</b>/<b>epsilon</b> to
  33. * <b>signal</b> based on the provided <b>random</b> value in [0.0, 1.0[.
  34. * The epsilon value must be between ]0.0, 1.0]. delta_f must be greater
  35. * than 0. */
  36. int64_t
  37. add_laplace_noise(int64_t signal_, double random_, double delta_f,
  38. double epsilon)
  39. {
  40. int64_t noise;
  41. /* epsilon MUST be between ]0.0, 1.0] */
  42. tor_assert(epsilon > 0.0 && epsilon <= 1.0);
  43. /* delta_f MUST be greater than 0. */
  44. tor_assert(delta_f > 0.0);
  45. /* Just add noise, no further signal */
  46. noise = sample_laplace_distribution(0.0,
  47. delta_f / epsilon,
  48. random_);
  49. /* Clip (signal + noise) to [INT64_MIN, INT64_MAX] */
  50. if (noise > 0 && INT64_MAX - noise < signal_)
  51. return INT64_MAX;
  52. else if (noise < 0 && INT64_MIN - noise > signal_)
  53. return INT64_MIN;
  54. else
  55. return signal_ + noise;
  56. }