Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this numpy array comparison fail?

Tags:

numpy

pytest

I try to compare the results of some numpy.array calculations with expected results, and I constantly get false comparison, but the printed arrays look the same, e.g:

def test_gen_sine():
  A, f, phi, fs, t = 1.0, 10.0, 1.0, 50.0, 0.1
  expected = array([0.54030231, -0.63332387, -0.93171798, 0.05749049, 0.96724906])
  result = gen_sine(A, f, phi, fs, t)
  npt.assert_array_equal(expected, result)

prints back:

>                   raise AssertionError(msg)
E                   AssertionError: 
E                   Arrays are not equal
E                   
E                   (mismatch 100.0%)
E                    x: array([ 0.540302, -0.633324, -0.931718,  0.05749 ,  0.967249])
E                    y: array([ 0.540302, -0.633324, -0.931718,  0.05749 ,  0.967249])

My gen_sine function is:

def gen_sine(A, f, phi, fs, t):  
  sampling_period = 1 / fs
  num_samples = fs * t
  samples_range = (np.arange(0, num_samples) * 2 * f * np.pi * sampling_period) + phi
  return A * np.cos(samples_range)

Why is that? How should I compare the two arrays? (I'm using numpy 1.9.3 and pytest 2.8.1)

like image 345
Luftzig Avatar asked Oct 10 '15 12:10

Luftzig


1 Answers

The problem is that np.assert_array_equal returns None and does the assert statement internally. It is incorrect to preface it with a separate assert as you do:

assert np.assert_array_equal(x,y)

Instead in your test you would just do something like:

import numpy as np
from numpy.testing import assert_array_equal

def test_equal():
    assert_array_equal(np.arange(0,3), np.array([0,1,2]) # No assertion raised
    assert_array_equal(np.arange(0,3), np.array([2,0,1]) # Raises AssertionError

Update:

A few comments

  • Don't rewrite your entire original question, because then it was unclear what an answer was actually addressing.

  • As far as your updated question, the issue is that assert_array_equal is not appropriate for comparing floating point arrays as is explained in the documentation. Instead use assert_allclose and then set the desired relative and absolute tolerances.

like image 85
JoshAdel Avatar answered Nov 08 '22 15:11

JoshAdel