Show HN: Rust library for numerical integration of real-valued functions

2 days ago (github.com)

Integrate is a fast, small, lightweight Rust library for performing numerical integration of real-valued functions. It is designed to integrate functions, providing a simple and efficient way to approximate definite integrals using various numerical methods.

Integrate supports a variety of numerical integration techniques: - Newton-Cotes methods:

  - Rectangle Rule.
  - Trapezoidal Rule.
  - Simpson's Rule.
  - Newton's 3/8 Rule.

- Gauss quadrature methods:

  - Gauss-Legendre.
  - Gauss-Laguerre.
  - Gauss-Hermite.
  - Gauss-Chebyshev First Kind.
  - Gauss-Chebyshev Second Kind.

- Adaptive Methods:

  - Adaptive Simpson's method

- Romberg’s method.

> Does the function oscillate over the region of integration? If it does, then make sure that the step size is chosen to be smaller than the wave length of the function.

Nyquist limit, but for numerical integration?

  • One way to think about is that these techniques work by integrating exactly the polynomial that interpolates the function where you're sampling it, so you need to resolve the features of the function to get good accuracy.

  • The Nyquist sampling theorem is of course proved by considering a Fourier transform, which is given by an integral, so the relation to integration in general should not be surprising.

  • Well in both cases it comes down to aliasing I think (high frequency wave presents as low frequency wave with too big step size)

I think the project should be called "NIntegrate".

BTW, that is not a serious suggestion; it is just that Wolfram Language (aka Mathematica) has both `Integrate` and `NIntegrate` for symbolic and numeric integration, respectively.

It looks a bit sloppy to hardcode so many constants in a single file: `src/gauss_quadrature/legendre.rs`. Isn't it possible to generate them with the help of rust macros in the same way Julia uses metaprogramming?

  • Gaussian quadrature points are typically solved numerically. There's a good chance these ultimately came from a table.

    Additionally, compile time floating-point evaluation is limited. When I looked around recently, I didn't see a rust equivalent of gcem; any kind of transcendental function evaluation (which finding Gaussian quadrature points absolutely would require) would not allow compile-time evaluation.

  • Probably but that would slow down compilation a lot.

    • You wouldn't have to recompile them every time. What if you didn't necessarily use macros but auto-generated it in a file that you keep separate from the other code at the bottom?

    • What I would do in these cases is to define the general computation function, but special-case it to return the hard-coded value for specific common inputs if it's being evaluated at compile time. Then add a test to verify both behaviors.

I was always amazed that R can do:

  > integrate(dnorm, -Inf, +Inf)
  1 with absolute error < 9.4e-05

Can we do the same in this library?

  • It seems like it is lacking the functionality R's integrate has for handling infinite boundaries, but I suppose you could implement that yourself on the outside.

    For what it's worth,

        use integrate::adaptive_quadrature::simpson::adaptive_simpson_method;
        use statrs::distribution::{Continuous, Normal};
    
        fn dnorm(x: f64) -> f64 {
            Normal::new(0.0, 1.0).unwrap().pdf(x)
        }
        
        fn main() {
            let result = adaptive_simpson_method(dnorm, -100.0, 100.0, 1e-2, 1e-8);
            println!("Result: {:?}", result);
        }
    

    prints Result: Ok(1.000000000053865)

    It does seem to be a usability hazard that the function being integrated is defined as a fn, rather than a Fn, as you can't pass closures that capture variables, requiring the weird dnorm definition

  • for ]-inf, inf[ integrals, you can use Gauss Hermite method, just keep in mind to multiply your function with exp(x^2).

        use integrate::{
            gauss_quadrature::hermite::gauss_hermite_rule,
        };
        use statrs::distribution::{Continuous, Normal};
    
        fn dnorm(x: f64) -> f64 {
            Normal::new(0.0, 1.0).unwrap().pdf(x)* x.powi(2).exp()
        }
    
        fn main() {
            let n: usize = 170;
            let result = gauss_hermite_rule(dnorm, n);
            println!("Result: {:?}", result);
        }
    
    

    I got Result: 1.0000000183827922.

  • How many evaluations of the underlying function does it make? (Hoping someone will fire up their R interpreter and find out.)

    Or, probably, dnorm is a probability distribution which includes a likeliness function, and a cumulative likeliness function, etc. I bet it doesn't work on arbitrary functions.

    • R integrate is just a wrapper around quadpack. It works with arbitrary functions, but arguably dnorm is pretty well behaved.

In the rectangle method, there is "let x = a + i * h + (h / F1::from(2)...)"

I didn't check, but I wonder if it is not better to do x = a + (i+0.5)*h... My reasoning is that if "i" is very big, then i * h can be much bigger than h/2 and thus h/2 may be eaten by numerical precision when added to i*h... And then you have to convince the optimizer to do it the way you want. But well, it's late...

  • herbie recommends `fma(h, (i + 0.5), a)`, but also doesn't report any accuracy problems with the original either

    • yeah, fused mul-add is certainly better. Dunno how one epxresses that in rust though :-) Ahhh seems like there at least f64::mul_add() in stdlib :-)

I don't see any explicit SIMD in here. Is the rust compiler able to emit SIMD instructions automatically in cases like this? (I guess I could compile and disassemble to check... )

  • In my experience Rust is very good about using simd for loading and not great at using it automatically for math. This is from some experimentation at work and checking disassembly so ymmv

    There are common library extensions for that.

Thanks for showing this! It is very motivating to develop (and finish) my Raku numerical integration project.

  • Thanks! That’s awesome to hear—I’d love to see how your Raku numerical integration project turns out!

    You can email me if you want to, I'll be happy to help.

Is there a technical reason to now allow closures as the integrand?

  • Mayve because they aren't guaranteed to be actual functions (in the mathematical sense) and could return random values

    • The Fn trait could be used, which prevents mutation, but allows a lot of useful closures. I should note, a motivated user could provide a junk function no matter what the type accepted is