0

Basically I have a number say 5.112 I want to subtract it in each iteration by 0.001 like 5.111, 5.110, 5.109, 5.108 etc.

Currently, I am thinking of using the split method to separate the number form decimal point and then subtract the 1st index by 1 and join.

I am just wondering If there is any other better way of doing this.

Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
  • 4
    Why not using a for loop and actually subtracting `0.001`? – Anwarvic Sep 17 '20 at 16:00
  • 1
    @Anwarvic Because [floating point math is (probably) broken](https://stackoverflow.com/q/588004/4518341) (me paraphrasing the question's title) – Tomerikoo Sep 17 '20 at 16:21

3 Answers3

2

Floats are imprecise (see Frank's answer and Is floating point math broken?).

Use decimal instead.

from decimal import Decimal as D

x = D('5.112')
mille = D('.001')
for i in range(5):
    x -= mille
    print(x)

Output:

5.111
5.110
5.109
5.108
5.107
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

If you were to do

x = 5.112
while True:
    x -= .001
    print(x)

You would quickly see the problems with floating point numbers and accumulating roundoff errors. The easiest method to avoid this is to instead calculate 5.112 - i * .001, where i is the number of subtractions you've performed so far.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
  • 1
    On my system, `5.112 - 4 * .001` is `5.1080000000000005`. Use `decimal` instead. I posted [my own answer](https://stackoverflow.com/a/63941991/4518341). – wjandrea Sep 17 '20 at 16:06
  • You identified the problem correctly, but your solution suffers from the same problem... – Tomerikoo Sep 17 '20 at 16:25
0

You can use numpy and list comprehension, like so:

import numpy
start = 5.112
[start-val for val in numpy.arange(0, 0.1, 0.001)]

You just need to know how many times you want to perform this operation.

roarkz
  • 811
  • 10
  • 22