Skip to content

Make use of composed functions and temporaries #1230

@andrjohns

Description

@andrjohns

Description

There are several places throughout the math library where arithmetic is being used in place of the composed functions and constants. There are also places where temporary variables could be used in place of repeated calculations.

An example of this can be seen in: prim/scal/fun/lub_constrain:

  if (x > 0) {
    T exp_minus_x = exp(-x);
    inv_logit_x = 1.0 / (1.0 + exp_minus_x);
    // Prevent x from reaching one unless it really really should.
    if ((x < std::numeric_limits<double>::infinity()) && (inv_logit_x == 1))
      inv_logit_x = 1 - 1e-15;
  } else {
    T exp_x = exp(x);
    inv_logit_x = 1.0 - 1.0 / (1.0 + exp_x);
    // Prevent x from reaching zero unless it really really should.
    if ((x > -std::numeric_limits<double>::infinity()) && (inv_logit_x == 0))
      inv_logit_x = 1e-15;
  }

Which could be updated to:

  T inv_logit_x;
  if (x > 0) {
    inv_logit_x = inv_logit(x);
    // Prevent x from reaching one unless it really really should.
    if ((x < INFTY) && (inv_logit_x == 1))
      inv_logit_x = 1 - 1e-15;
  } else {
    inv_logit_x = inv_logit(x);
    // Prevent x from reaching zero unless it really really should.
    if ((x > NEGATIVE_INFTY) && (inv_logit_x == 0))
      inv_logit_x = 1e-15;
  }

I'll be working through this in my spare time, and will break the PRs into multiple parts. I'll update this issue as I go

  • prim
    • scal
      • fun
      • prob
    • mat
      • fun
      • prob
    • arr
      • fun

Current Version:

v2.19.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions