如何修复使用浮点数进行计算时出现的计算错误?

huangapple go评论95阅读模式
英文:

How to fix calculation error in go math operations with floats?

问题

我需要将一个值(以度为单位)归一化到某个范围内。我需要通过除以360来获取除法的余数。

func testFunc(t *testing.T) {

	v := -1050.6
	n := int(v / 360)
	f := v - float64(n)*360

	fmt.Printf("f: %v\n", f)
}

我期望得到的值是-330.6,但实际得到的值是-330.5999999999999。这是在执行v - float64(n)*360时发生的。有没有办法消除这个误差?

英文:

I need to normalise a value (degrees) to have it in some range. I need to get a reminder of division by 360.

func testFunc(t *testing.T) {

	v := -1050.6
	n := int(v / 360)
	f := v - float64(n)*360

	fmt.Printf("f: %v\n", f)
}

The value I expect is -330.6 the value I get is -330.5999999999999. This happens when I do v - float64(n)*360. Is there any way to get rid of this error?

答案1

得分: 1

你可以尝试这样写(保留小数点后两位):

fmt.Println(math.Round(f * 100) / 100)
英文:

You can try this (2 digits after comma):

fmt.Println(math.Round(f * 100) / 100)

huangapple
  • 本文由 发表于 2022年2月10日 19:38:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/71064434.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定