Rounding floats so that they sum to precisely 1

后端 未结 5 1962
臣服心动
臣服心动 2020-12-02 00:51

I have a rather gnarly bit of code that must more-or-less randomly generate a bunch of percentages, stored as decimal floats. That is, it decides that material one makes up

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 01:40

    floats are are represented by powers of two. From the python docs: "Unfortunately, most decimal fractions cannot be represented exactly as binary fractions"

    http://docs.python.org/2/tutorial/floatingpoint.html

    EDIT: Maybe instead of actually trying to get to 1.0000000000000000000000 you should determine an acceptable level of error by cutting off anything after the third decimal place. You can be relatively certain that the value added to 1. Using this concept you could accept any answer greater than 0.999 and less than 1.001.

    This may not be perfect but it might be a good workaround to get you past your problem.

提交回复
热议问题