AlphaF20
AlphaF20

Reputation: 603

How to realize numpy.allclose in Fortran?

In numpy, there is an allclose function which compares two tensors per element. The inputs are mainly two tensors and thresholds.

If I do it in Fortran, if I use arrays A and B as the arguments of the subroutines, I need to declare the dimensions of the arrays in the subroutine first, before doing subsequent operations. This would require me to put the dimensions of arrays into the argument. And complicates the input. Is there any simpler way to realize something like allclose in Fortran?

Upvotes: 0

Views: 89

Answers (1)

AlphaF20
AlphaF20

Reputation: 603

Thanks for the comments from Ian Bush. The following code works.

Program compare_array_test
  
    real :: A(2,2), B(2,2), E(2,2,2), F(2,2,2)
    complex :: C(2,2), D(2,2)
    real :: tol
  
    A = 1.0
    B = 1.0
    A(1,1) = 1.01
  
    tol = 0.0001
  
    If( All( Abs( A - B ) < tol ) ) Then
      write (*,*) 'within the threshold' 
    else
      write (*,*) 'above the threshold'      
    end if 
    
    tol = 0.1
  
    If( All( Abs( A - B ) < tol ) ) Then
      write (*,*) 'within the threshold' 
    else
      write (*,*) 'above the threshold'      
    end if      
  
    C = (1.0, 1.0)
    D = (1.0, 1.0)
    C(1,1) = (1.01, 1.00)
  
    tol = 0.0001
  
  
    If( All( cabs( C - D ) < tol ) ) Then
      write (*,*) 'within the threshold' 
    else
      write (*,*) 'above the threshold'      
    end if 
    
    tol = 0.1
  
    If( All( cabs( C - D ) < tol ) ) Then
      write (*,*) 'within the threshold' 
    else
      write (*,*) 'above the threshold'      
    end if     


    E = 1.0
    F = 1.0
    E(1,1,1) = 1.01
  
    tol = 0.0001
  
    If( All( Abs( E - F ) < tol ) ) Then
      write (*,*) 'within the threshold' 
    else
      write (*,*) 'above the threshold'      
    end if 
    
    tol = 0.1
  
    If( All( Abs( E - F ) < tol ) ) Then
      write (*,*) 'within the threshold' 
    else
      write (*,*) 'above the threshold'      
    end if     

end program    

Upvotes: 1

Related Questions