Find common factor to convert list of floats to list of integers

前端 未结 2 1750
鱼传尺愫
鱼传尺愫 2021-01-22 21:05

I have a list of floats which comes from some other function. What I know is that in ideal world there exist a common factor which can be used to multiply each term to obtain li

2条回答
  •  遇见更好的自我
    2021-01-22 21:33

    The brute force solution. Still looking for something more universal...

    def find_int(arr):
        test = False
        epsilon = 1e-15
        maxint = 1000
        for i in range(2, maxint, 1):
            for item in arr:
                if abs(i*item-round(i*item)) < epsilon:
                    test = True
                else:
                    test = False
                    break
            if test:
                print i
                return [int(round(i*item)) for item in arr]
        print "Could not find one"
        return arr
    

提交回复
热议问题