dongshushi5579 2017-02-19 15:14
浏览 101
已采纳

Golang怪异big.Int行为,位数很少

I am trying to calculate the GCD of two numbers via the Euclidean method, and noticed weird behavior. Although I am passing the value of the number to the function, the numbers are modified by the function for numbers with low number of bits (usually less than 64). Could anyone clarify if this is a mistake on my behalf or is it expected behavior? You can check the code in the playground here: Golang playground example

I thought the expected behavior is that no values should be changed by passing them to my functions. Thanks for any help, I couldn't find any other occurrences like this in the last day of searching.

  • 写回答

1条回答 默认 最新

  • dongquming3255 2017-02-19 16:41
    关注

    big.Int is a struct containing nat, which is defined as type nat []Word so, while you are indeed copying the big.Int, the slice inside it is effectively a shallow copy (underlying storage for slice is same)

    For why the bigger bit widths don't exhibit the problem, not sure.

    Possibly it requires a reallocation somewhere and that creates a new []Word thereby leaving the original in tact.

    This is also probably why the stdlib generally returns *big.Int, since a value isn't really copyable

    here's a version on play that properly copies the big.Int values. The key difference being:

    a := new(big.Int).Set(x)
    b := new(big.Int).Set(y)
    

    (and using pointers in general as values aren't particularly useful)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序