ForVikaV1

Sep 20th, 2020 (edited)
730
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import math
2.
3.
4. def main():
5.     N_dec = input('Введите число в десятичной системе счисления: ')
6.     try:
7.         N_dec = float(N_dec)
8.     except ValueError as err:
9.         print("Введено не число в десятичной системе!")
10.         raise(err)
11.
12.     base = input('Введите систему счисления, в которую перевести это число: ')
13.     try:
14.         base = int(base)
15.     except ValueError as err:
16.         print("Введено не целое число в десятичной системе!")
17.         raise(err)
18.
19.     N_base = from_dec_to_base(N_dec, base)
20.     print(f'Число {N_dec} в {base}-ичной системе счисления равно {N_base}')
21.
22.
23. def from_dec_to_bin(dec_num: float, accuracy: int = 10) -> str:
24.     integer_part = math.floor(dec_num)
25.     fractional_part = dec_num - integer_part
26.
27.     # Integer with binary representation similar to binary fractional part
28.     bin_fractional_part = 0
29.     n = 0.5
30.     for _ in range(accuracy):
31.         if n <= fractional_part:
32.             bin_fractional_part += 1
33.             fractional_part -= n
34.         bin_fractional_part = bin_fractional_part << 1
35.         n = n / 2
36.     bin_fractional_part = bin_fractional_part >> 1
37.
38.     # Binary represented right-aligned fractional part filled by leading zeroes
39.     return f'{integer_part:b}.{bin_fractional_part:0>{accuracy}b}'
40.
41.
42. def from_dec_to_base(dec_num: float, base: int, accuracy: int = 10) -> str:
43.     # Special function is 4 times faster!
44.     # if base == 2:
45.     #     return from_dec_to_bin(dec_num, accuracy)
46.
47.     integer_part = math.floor(dec_num)
48.     fractional_part = dec_num - integer_part
49.
50.     base_integer_part = []
51.     max_power = math.floor(math.log(integer_part, base))
52.     n = base ** max_power
53.     for _ in range(max_power + 1):
54.         value = integer_part // n
55.         integer_part -= n * value
56.         n = n // base
57.         base_integer_part.append(str(value))
58.     base_integer_part = "".join(base_integer_part)
59.
60.     base_fractional_part = []
61.     n = base ** -1
62.     for _ in range(accuracy):
63.         value = int(fractional_part / n)
64.         fractional_part -= value * n
65.         n = n / base
66.         base_fractional_part.append(str(value))
67.     base_fractional_part = "".join(base_fractional_part)
68.
69.     return f'{base_integer_part}.{base_fractional_part}'
70.
71.
72. def from_base_to_dec(base_num: str, base: int) -> float:
73.     pass
74.
75.
76. if __name__ == '__main__':
77.     main()
RAW Paste Data