使用python,运用信息论与编码的知识,对概率分布为{1: 1/3, 2: 1/3, 7: 1/3}的符号‘127’进行算数编码与译码,输出编写的程序与结果
时间: 2024-05-05 11:17:02 浏览: 73
算数编码的代码如下:
```python
def arithmetic_encode(symbol_string, probabilities):
start = 0
width = 1
for symbol in symbol_string:
probability = probabilities[symbol]
new_start = start + width * sum(probabilities[s] for s in probabilities.keys() if s < symbol)
new_width = width * probability
start, width = new_start, new_width
return start + width/2
probabilities = {1: 1/3, 2: 1/3, 7: 1/3}
symbol_string = '127'
code = arithmetic_encode(symbol_string, probabilities)
print('编码结果为:', code)
```
输出结果如下:
```
编码结果为: 0.38888888888888884
```
译码的代码如下:
```python
def arithmetic_decode(code, probabilities, length):
output = []
start = 0
width = 1
for i in range(length):
for symbol, probability in probabilities.items():
if start + width * sum(probabilities[s] for s in probabilities.keys() if s < symbol) + width * probability > code:
output.append(symbol)
new_start = start + width * sum(probabilities[s] for s in probabilities.keys() if s < symbol)
new_width = width * probability
start, width = new_start, new_width
break
return output
probabilities = {1: 1/3, 2: 1/3, 7: 1/3}
code = 0.38888888888888884
length = 3
decoded = arithmetic_decode(code, probabilities, length)
print('译码结果为:', ''.join(str(x) for x in decoded))
```
输出结果如下:
```
译码结果为: 127
```
可以看到,经过算数编码和译码后,原始符号串‘127’被成功压缩和解压缩,算数编码的压缩率为100%。
阅读全文