英文:
How can I add two arbitrary large numbers in Go?
问题
当我将两个非常大的浮点数相加时,得到了错误的输出。我该如何在Go语言中解决这个问题?PHP中有bcadd
函数。
var a float64 = 12959653081233191386469183112744623843489338314724603559902557916087872259523073406440221030943397504960564327459290759156915189196536625503825265749393408
var b float64 = 1302494993937727547864388263735304125561725318351673964024430436931705604299209078600534362879064309484886438718428990856894006118477463552
// 正确的值: 12959653081233192688964177050472171707877602050028729121627876267761836283953510338145825330152476105494927206523600244043353907625527482397831384226856960
// 实际输出: 12959653081233192875034890470147535688504496869357889916160064603715259716015001328389483087182344476999836189247073027598559438829669033382689401152208896
fmt.Println(strconv.FormatFloat(a+b, 'f', 0, 64))
请注意,我只翻译了代码部分,其他内容不做翻译。
英文:
When I add two very large floats I get the wrong output. How can I do this in Go? PHP has the bcadd
function.
var a float64 = 12959653081233191386469183112744623843489338314724603559902557916087872259523073406440221030943397504960564327459290759156915189196536625503825265749393408
var b float64 = 1302494993937727547864388263735304125561725318351673964024430436931705604299209078600534362879064309484886438718428990856894006118477463552
// correct value: 12959653081233192688964177050472171707877602050028729121627876267761836283953510338145825330152476105494927206523600244043353907625527482397831384226856960
// actual output: 12959653081233192875034890470147535688504496869357889916160064603715259716015001328389483087182344476999836189247073027598559438829669033382689401152208896
fmt.Println(strconv.FormatFloat(a+b, 'f', 0, 64))
答案1
得分: 5
bcadd
及其相关函数是任意精度算术函数(这就是为什么它们操作字符串而不是浮点数)。浮点数具有有限的精度。实际上,bcmath
提供的精度比浮点数更高。
在PHP中,你可以使用bcadd
函数来进行任意精度的加法运算。如果你在使用Go语言,可以使用math/big
包来实现类似的功能。
英文:
> who can help me? in php has bcadd function
bcadd
and its friends are arbitrary precision arithmetic functions (that's why they operate on strings and not floats). A float has limited precision. In effect, bcmath
offers infinitely more precision than a float.
Use math/big
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论