Skip to content

Random instance for Complex numbers #74

@lehins

Description

@lehins

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:

-- | /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:

-- | /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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions