P5.js: randomGaussian() with sd=0

Created on 8 Sep 2020  路  10Comments  路  Source: processing/p5.js

When using randomGaussian(mean, 0), the function should return the mean. It does not.

From my tests, it looks like the sd is replaced with a value of 1.

It might not sound useful to add this functionality but my animation has a slider to control the randomness. When it is at 0, I want the animation to be fully deterministic.

Most appropriate sub-area of p5.js?

  • [ ] Accessibility (Web Accessibility)
  • [ ] Color
  • [ ] Core/Environment/Rendering
  • [ ] Data
  • [ ] Dom
  • [ ] Events
  • [ ] Image
  • [ ] IO
  • [x] Math
  • [ ] Typography
  • [ ] Utilities
  • [ ] WebGL
  • [ ] Other (specify if possible)

Details about the bug:

  • p5.js version: 0.10.2
  • Web browser and version: Chrome 85.0.4183.83
  • Operating System: MacOS 10.15.6
  • Steps to reproduce this: randomGaussian(42, 0)
bug

All 10 comments

This line here should check existence of sd instead of using the || operator which will evaluate 0 as falsy thus changing the value to 1.

It looks like you can use the null-coalescing operator (const s = sd ?? 1;), which is made specially for this case (and "").
It is from ES2020 though, so depending on how the library is built, might not be a good idea. https://caniuse.com/mdn-javascript_operators_nullish_coalescing

The library does use babel support newer syntax although I'm not sure if babel support nullish coalescing yet. @outofambit Do you perhaps know more about the possibility here?

I took a quick look at this and while our babel build process does support this, our linter isn't setup to handle it. I think we would need to use https://github.com/babel/babel-eslint for eslint's parsing for that to longer be an issue. (Right now eslint uses a built-in parser, which doesn't include features that aren't officially part of the JS spec.

Does setting env in .eslintrc to es2020 helps the linting pass? I have a different project that uses the related optional chaining operator (?.) that passes linting when set to es2020.

How about using default parameters(randomGaussian = function(mean, sd = 1)), see https://caniuse.com/mdn-javascript_functions_default_parameters . Or const s = sd === 0 ? 0 : sd || 1;?

Yes, I think default parameters could be a good solution.

Cool! Setting sd to 1 with default parameters, removing s altogether and replacing it with sd. I think I can send a pull request in a couple of hours.

Does setting env in .eslintrc to es2020 helps the linting pass

This might work! i think we'll have to upgrade eslint to use that, but that's not a big deal.

@outofambit Can you have a look at #4822 and if that works we can defer changing eslint rules until we need it.

Was this page helpful?
0 / 5 - 0 ratings