My code is limited in speed by the following rebinning subroutine. Code is also here on Github: futils/futils.f90 at main · Nicholaswogan/futils · GitHub . Suppose you have values defined on some bins. This subroutine can rebin to a new set of bins.

I’m wondering if someone knows of an implementation that is faster? or if they can spot optimizations that I could make to the current version? Thanks!

```
subroutine rebin(old_bins, old_vals, new_bins, new_vals, ierr)
real(dp), intent(in) :: old_bins(:)
real(dp), intent(in) :: old_vals(:)
real(dp), intent(in) :: new_bins(:)
real(dp), intent(out) :: new_vals(:)
integer, optional, intent(out) :: ierr
integer :: i, j, l, n_old, n_new
real(dp) :: b1, b2
n_old = size(old_vals)
n_new = size(new_vals)
! option to check inputs.
if (present(ierr)) then
ierr = 0
! check shape
if (n_old+1 /= size(old_bins)) then
ierr = -1
return
endif
if (n_new+1 /= size(new_bins)) then
ierr = -2
return
endif
! check that new bins overlap with the old bins
if (new_bins(1) < old_bins(1) .and. new_bins(2) < old_bins(1)) then
ierr = -3
return
endif
if (new_bins(n_new) > old_bins(n_old+1) .and. new_bins(n_new+1) > old_bins(n_old+1)) then
ierr = -4
return
endif
! check that bins are all increasing
do i = 1,n_old
if (old_bins(i+1) <= old_bins(i)) then
ierr = -5
return
endif
enddo
do i = 1,n_new
if (new_bins(i+1) <= new_bins(i)) then
ierr = -6
return
endif
enddo
endif
new_vals = 0.0_dp
l = 1
do i = 1,n_new
b1 = new_bins(i+1) - new_bins(i)
do j = l,n_old
! four different cases
! ______ (old bin)
! ________ (new bin)
if (old_bins(j) <= new_bins(i) .and. &
old_bins(j+1) > new_bins(i) .and. old_bins(j+1) < new_bins(i+1)) then
b2 = old_bins(j+1) - new_bins(i)
new_vals(i) = new_vals(i) + (b2/b1)*old_vals(j)
! ____ (old bin)
! ________ (new bin)
elseif (old_bins(j) >= new_bins(i) .and. old_bins(j+1) <= new_bins(i+1)) then
b2 = old_bins(j+1) - old_bins(j)
new_vals(i) = new_vals(i) + (b2/b1)*old_vals(j)
! ____ (old bin)
! ________ (new bin)
elseif (old_bins(j) >= new_bins(i) .and. &
old_bins(j) < new_bins(i+1) .and. old_bins(j+1) > new_bins(i+1)) then
b2 = new_bins(i+1) - old_bins(j)
new_vals(i) = new_vals(i) + (b2/b1)*old_vals(j)
! ________ (old bin)
! ____ (new bin)
elseif (old_bins(j) < new_bins(i) .and. old_bins(j+1) > new_bins(i+1)) then
new_vals(i) = new_vals(i) + old_vals(j)
! _____ (old bin)
! ____ (new bin)
elseif (old_bins(j) > new_bins(i+1)) then
! time to move onto the next new_bin
l = j - 1
exit
else
! nothing
endif
enddo
enddo
end subroutine
```