haskell / haskell/random

`Random` instance for `Complex` numbers

Open
#74 10 comments 0 reactions 0 assignees View on GitHub
Dominant language
Haskell
Stars
59
Forks
56
PR merge metrics
No merged PRs in 30d

Description

Few of us have mentioned that `Random` is no longer useful, because `Uniform` and `UniformRange` was introduced as a more correct interface. `Complex` is an example of a type where `Random` can be very useful. We can't compare them and we can't produce a uniform distribution due to infinite many values, so there never can be neither `Uniform` nor `UniformRange` instances. But should it also mean that we can't have random complex numbers at all? For example I can see this as a sensible instance for complex numbers:

```haskell
-- | /Note/ - `randomR (z1, z2)` will produce values in a rectangle with a diagonal
-- defined by a difference of `z1 - z2` and `random` will rely on `a` to produce value for
-- both real and imaginary parts.
instance Random a => Random (Complex a) where
randomR ((al :+ bl), (ah :+ bh)) = runState $
(:+) <$> state (randomR (al, ah)) <*> state (randomR (bl, bh))
random = runState $ (:+) <$> state random <*> state random
```
or even better and more useful alternative could be this definition:
```haskell
-- | /Note/ - `randomR` produces values in the annulus between two complex numbers and
-- `random` generates values within the unit circle.
instance (RealFloat a, Random a) => Random (Complex a) where
randomR (z1, z2) = runState $
mkPolar <$> state (randomR (magnitude z1, magnitude z2)) <*> state (randomR (0, 2*pi))
random = random = runState $ mkPolar <$> state (randomR (0, 1)) <*> state (randomR (0, 2*pi))
```

Thoughts?

_Note_ - `randomR (0, 2*pi)` would need to be adjusted not to include `2*pi`, but that is an implementation detail

Contributor guide

No contributing guide indexed for this repository

Research direction

No files, tests, or entry points are mentioned. Start by reviewing the existing Random, Uniform, and UniformRange interfaces and the Complex type; a contribution would first need an agreed definition for randomR and random, followed by an implementation and tests for the chosen semantics.

Written by the indexing model from the issue text.

Assessment

Tech stack
haskell
Domain
data
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.