package sqrt
func Sqrt(num int64) float64 {
const precision = 0.001
i := int64(1)
for ; i*i <= num; i++ {
}
result := float64(i - 1)
for ; result*result <= float64(num); result += precision {
}
return result - precision
}
package sqrt
import "testing"
var sqrtTests = []struct {
num int64
result float64
}{
{9, 3.0},
{10, 3.162},
{5, 2.236},
{97, 9.848},
{16, 4.0},
}
func TestSqrt(t *testing.T) {
for _, tt := range sqrtTests {
if got := Sqrt(tt.num); got != tt.result {
t.Errorf("got: Sqrt(%d)=%f, want: Sqrt(%d)=%f", tt.num, got, tt.num, tt.result)
}
}
}
[okumar@oshank-pc:sqrt]🎩 go test
--- FAIL: TestSqrt (0.00s)
sqrt_test.go:19: got: Sqrt(10)=3.162000, want: Sqrt(10)=3.162000
sqrt_test.go:19: got: Sqrt(5)=2.236000, want: Sqrt(5)=2.236000
sqrt_test.go:19: got: Sqrt(97)=9.848000, want: Sqrt(97)=9.848000
FAIL
exit status 1
FAIL <http://github.com/oshankfriends/go-examples/sqrt|github.com/oshankfriends/go-examples/sqrt> 0.001s
NobbZ
(Norbert Melzer)
2
The difference is probably somewhere behind the stripped part. One doesn’t compare floating point numbers with the equality comparator.
One does check if they are within an allowed delta to the target value.
2 Likes
Replace it with a call to a function like this:
func EqualFloat(a, b, precision float64) bool {
diff := a - b
if diff < 0.0 {
diff = -diff
}
return diff < precision
}
1 Like
system
(system)
Closed
4
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.