0

I need to write a function that converts a decimal fraction number into base 2 fraction number in R. e.g. f(0.125) # 0.001

What I did: I searched for the related functions in R packages:

DescTools::DecToBin(0.125) # ""
DescTools::DecToBin("0.125") # Not compatible with requested type: [type=character; target=integer].

0.125 is:

(0 * 2^(-1)) + (0 * 2^(-2)) + (1 * 2^(-3)) # 0.125
(0 * 1/2) + (0 * (1/2)^2) + (1 * (1/2)^3) # 0.125
(0 * 0.5) + (0 * (0.5)^2) + (1 * 0.5^3) # 0.125

The reverse side is the following and was solved here:
How to convert a binary fraction number into decimal fraction number in R?

Hence, a reverse-wind or something new hack seems to be necessary to overcome the problem.

Erdogan CEVHER
  • 1,788
  • 1
  • 21
  • 40
  • You can use `R.utils::IntToBin`, I suggest twice: once to get the whole, and once on the fractional component multiplied by some high base-10 number (e.g., `1e8`) to get as much accuracy as you need. – r2evans Jun 10 '19 at 13:39
  • @r2evans This does not work for the fractional part. By multiplying it with 1e8, you get the integer representation of 10^8*mantissa. But you cant simply deduce the binary decomposition from that. What must be done is to multiply it by a large power of 2 (say 2^20 to get the equivalent of 6 decimal digits). Bit 19 corresponds 2^-1, bit 18 to 2^-2 and so on. – Alain Merigot Jun 10 '19 at 14:00
  • I was suggesting multiplying and then converting with `IntToBin`, not just multiplying, sorry for missing that clarity. – r2evans Jun 10 '19 at 14:01
  • `R.utils::intToBin(10) # "1010"` and `R.utils::intToBin(0.125) # "0"`. The function `intToBin` is with lowercase i. – Erdogan CEVHER Jun 10 '19 at 14:13
  • @r2evans `R.utils::intToBin(cwhmisc::frac(4.125) * 1e8) # R.utils::intToBin(0.125 * 1e8) = R.utils::intToBin(12500000) = "101111101011110000100000"`, so what? – Erdogan CEVHER Jun 10 '19 at 17:14

0 Answers0