4

I've wrapped the 'NumericalIntegration' C++ library in Haskell. Here is the latest version of the package (the version on Hackage is older).

Here is the main part of the C++ code :

class Integrand {
 private:
  std::function<double(double)> f;

 public:
  Integrand(std::function<double(double)>& f_) : f(f_) {}
  double operator()(const double x) const { return f(x); }
};

double integration(double f(double),
                   double lower,
                   double upper,
                   double relError,
                   int subdiv,
                   double* errorEstimate,
                   int* errorCode) {
  // Define the integrand.
  std::function<double(double)> f_ = [&](double x) { return f(x); };
  Integrand integrand(f_);
  // Define the integrator.
  Eigen::Integrator<double> integrator(subdiv);
  // Define a quadrature rule.
  Eigen::Integrator<double>::QuadratureRule rule =
      Eigen::Integrator<double>::GaussKronrod201;
  // Define the desired absolute error.
  double absError = 0.0;
  // Integrate.
  double result = integrator.quadratureAdaptive(integrand, lower, upper,
                                                absError, relError, rule);
  *errorEstimate = integrator.estimatedError();
  *errorCode = integrator.errorCode();
  return result;
}

And here is the main part of the Haskell code:

foreign import ccall safe "wrapper" funPtr
    :: (Double -> Double) -> IO (FunPtr (Double -> Double))

foreign import ccall safe "integration" c_integration
    :: FunPtr (Double -> Double) -> Double -> Double -> Double -> Int
    -> Ptr Double -> Ptr Int -> IO Double

-- | Numerical integration.
integration :: (Double -> Double)       -- ^ integrand
            -> Double                   -- ^ lower bound
            -> Double                   -- ^ upper bound
            -> Double                   -- ^ desired relative error
            -> Int                      -- ^ number of subdivisions
            -> IO IntegralResult        -- ^ value, error estimate, error code
integration f lower upper relError subdiv = do
  errorEstimatePtr <- mallocBytes (sizeOf (0 :: Double))
  errorCodePtr <- mallocBytes (sizeOf (0 :: Int))
  fPtr <- funPtr f
  result <-
    c_integration fPtr lower upper relError subdiv errorEstimatePtr errorCodePtr
  errorEstimate <- peek errorEstimatePtr
  errorCode <- peek errorCodePtr
  let out = IntegralResult {_value = result, _error = errorEstimate, _code = errorCode}
  free errorEstimatePtr
  free errorCodePtr
  freeHaskellFunPtr fPtr
  return out

This works but there's a problem regarding the error code of the integration. When the integration is ok, the error code should be 0. Sometimes it is 0, as expected. But sometimes it is a huge integer number, nonsensical, though the integration is fine.

Would you have an idea about this issue? Why this strange error code? Is there something bad in my code? I'm not fluent in C++ (nor in Haskell). But apart this strange error code, the library seems to work very well.

12
  • What do you mean by "sometimes"? "For some inputs", or "nondeterministically some of the time" for inputs that have worked previously? What happens when you use the C++ version directly with the same test cases? Sep 18 at 14:40
  • I don't understand the rational to use pointers for returned values. Even an old compiler can return an aggregate struct containing all information. Not knowing about Haskell's type system, error in old C code are usually indicated by negative numbers, which translate to high positive values if the 2's complement is bit_casted to unsigned. Because native floating point has limited precision, in case of occurence of NaN or INF in intermediate calculations, the rest of the calculations are not considered reliable.
    – Red.Wave
    Sep 18 at 14:40
  • Nondeterministically, this is random. When I run an integration, and I rerun the same, the error code can change. I don't know how to use directly use the C++ library. Sep 18 at 14:42
  • 1
    struct integration_result{ int error; double value; double accuracy;}; that should be the return type. Now you can remove the pointers from the API. Next: the input to your API function needs to be a function pointer, so Daniel has a point in that regard. But the initializer for integrand can be f itself. You don't need the lambda here, because the signature is compatible. You certainly don't need to create an extra instance of std::function: Integrand integrand{f}; will do. But you don't even need that class, just integrator.quadratureAdaptive(f,/*..*/); is much better.
    – Red.Wave
    Sep 18 at 15:40
  • 1
    @Red.Wave Structs are somewhat more annoying (not impossible or even hard, just more annoying) to handle with the Haskell FFI than output-by-pointer. Sep 18 at 16:46

1 Answer 1

7

On the x86_64 platform, a Haskell Int is 64 bits while a C int is 32 bits. (A C long is 64 bits.) In your code, you are picking up garbage in the upper bytes and getting an absurdly large 64-bit integer whose lowest 32-bits are zero, no doubt.

Anyway, there's a module Foreign.C that contains newtypes CInt, CDouble, etc. that are intended to match the corresponding C types on the target platform, and I think it's considered good practice to always use those:

import Foreign
import Foreign.C

foreign import ccall safe "wrapper" funPtr
    :: (CDouble -> CDouble) -> IO (FunPtr (CDouble -> CDouble))

foreign import ccall safe "integration" c_integration
    :: FunPtr (CDouble -> CDouble) -> CDouble -> CDouble -> CDouble -> CInt
    -> Ptr CDouble -> Ptr CInt -> IO CDouble

Of course, since these are newtypes, there is the bother of wrapping and unwrapping, though usually fromIntegral takes care of that automatically, while also converting across bit sizes:

errorCode <- fromIntegral <$> peek errorCodePtr

But, as a less portable alternative, you could stick with Double and Int32 in your foreign import declarations, provided you are only targeting platforms where C ints are 32 bits.

Also note that, if you get the types right, then malloc is a type-safe alternative to mallocBytes:

errorCodePtr <- malloc

The type of the Ptr determines the correct number of bytes to allocate here.

4
  • Thanks! It works now. Would you whether it's possible to convert CDouble to Double? I would prefer Double in the result. Sep 18 at 15:08
  • 1
    @StéphaneLaurent people often use realToFrac for this, though that's actually problematic. Sep 18 at 15:15
  • @leftaroundabout Ah yes, I was looking for fromRealToFrac ^^ Sep 18 at 15:24
  • Thanks @leftaroundabout. I was thinking about this issue. If I want to return Double, I can check if the CDouble is NaN, in which case I return a NaN Double. I can also check if the CDouble is Infinity, in which case I return a Double Infinity. No ? Does it make sense ? Sep 19 at 2:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.