3

I'm trying to check in Python if a math.log(x, base) has decimal or not:

import math

# math.log(8, 2) = 3
print math.log(8)
print math.log(2)
print math.log(8) / math.log(2)
print 2.07944154168 % 0.69314718056
print math.log(8) % math.log(2)

Output is:

2.07944154168
0.69314718056
3.0
0.0
0.69314718056

Why does fourth print row return zero but fifth does not?

Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
glc78
  • 439
  • 1
  • 8
  • 20
  • 3
    Does this help? https://stackoverflow.com/questions/14763722/python-modulo-on-floats – Ray Toal Dec 16 '17 at 00:32
  • did you notice that % returns the same value of 0.69314718056, which is the second operator ??? a % b = b ... lol – mlwn Dec 16 '17 at 00:41
  • @mlwn Yes I did, but I don't know what to think about. – glc78 Dec 16 '17 at 00:58
  • @RayToal Helps to understand something, but how then can I check if log(x, base) gives result without decimal? – glc78 Dec 17 '17 at 10:53

2 Answers2

1

This is what I get using python 3

>>> print (math.log(8))
2.0794415416798357
>>> print (math.log(2))
0.6931471805599453
>>> print (math.log(8) / math.log(2))
3.0
>>> print (2.07944154168 % 0.69314718056)
0.0
>>> print (math.log(8) % math.log(2))
0.6931471805599452
>>> print (2.0794415416798357 % 0.6931471805599453)
0.6931471805599452

It looks like in your example (python 2 ?), the precision of math.log is not enough.

muratgu
  • 7,241
  • 3
  • 24
  • 26
1

This will probably be closed for being a duplicate, but just so one can see how this plays out:

>>> import math
>>> math.log(8)
2.0794415416798357
>>> math.log(2)
0.6931471805599453

Now let's say you need to compute math.log(8) % math.log(2). You need to compute the remainder after dividing math.log(2) into math.log(8). Let's see, does it go in 3 times?

  0.6931471805599453
+ 0.6931471805599453
+ 0.6931471805599453
--------------------
  2.0794415416798359

Woah! We overshot the value of 2.0794415416798357 which means it actually goes in TWO times:

  0.6931471805599453
+ 0.6931471805599453
--------------------
  1.3862943611198906

Okay so what is the remainder?

  2.0794415416798359
- 1.3862943611198906
--------------------
  0.6931471805599453

So TL;DR your remainder is close to math.log(2) because of rounding errors. It does not go in exactly three times. It goes in two times with just about math.log(2) left over.

Yes when you print the quotient it says 3.0 but again, this is all rounding error in floating point, which is not unique to Python.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • I understand what happens now. Maybe I should read [this](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) to go deeper as suggested in the [python module question](https://stackoverflow.com/questions/14763722/python-modulo-on-floats). What do you mean with TL;DR? – glc78 Dec 17 '17 at 12:59