Testing program

func TestAvg2(t *testing.T) {
	type test struct {
		data   []float64
		answer float64
	}

	tests := []test{
		test{[]float64{2, 2}, 2.00},
		test{[]float64{4, 4}, 4.00},
		test{[]float64{3, 3, 4}, 3.33},
		test{[]float64{3, 3, 5}, 3.67},
		test{[]float64{5, 5, 5}, 5.00},
		test{[]float64{-10, 10, 10, 11}, 5.25},
	}

	for _, v := range tests {
		x := Avg(v.data...)
		str := fmt.Sprintf("%.2f", x)
		fl, _ := strconv.ParseFloat(str, 64)
		if x != v.answer {
			t.Error("Expected", v.answer, "got", fl)
		}
	}
}

Results:
table_test.go:29: Expected 3.33 got 3.33
table_test.go:29: Expected 3.67 got 3.67

What’s wrong?

Rounding errors. Thats what floats are known for.

For floats one usually checks if the absolute of the difference between two values is lesser than or equal a certain threshold, and considers them equal if the difference is small enough.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.