生活随笔
收集整理的這篇文章主要介紹了
shannon编码
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
shannon碼不是最佳編碼,是香農(nóng)提出編碼理論后自己提出的一種編碼方式
shannon編碼主要分三個(gè)步驟
1.將字符按概率從大到小排序
2.將概率累加(除最小概率之外)
3.根據(jù)概率算出其信息熵確定碼長(zhǎng),根據(jù)碼長(zhǎng)將其累加概率轉(zhuǎn)化為2進(jìn)制碼即shannon碼
栗子:
| 碼字符: | A | B | C | D |
| 概率: | 0.4 | 0.3 | 0.2 | 0.1 |
| 累加: | 0 | 0.4 | 0.7 | 0.9 |
| 碼: | 00 | 01 | 101 | 1110 |
// Shannon.cpp : 定義控制臺(tái)應(yīng)用程序的入口點(diǎn)。
//#include "iostream"
#include "math.h"
#include "map"
#include "fstream"
#include <sstream>using namespace std;class shannon{
public:shannon(string file_name);void show();//TODO://string to_shannon_code(string str = "");//string to_word(string str = "");private:shannon(){};int make_code();//編碼string decimals_to_binary(double decimals, int figures);//10進(jìn)制小數(shù)轉(zhuǎn)2進(jìn)制數(shù)(小數(shù),位數(shù))int get_probability(string file_name);//從文本中分析各個(gè)字符概率multimap<double, string> word;//原始字符、概率multimap<string, string> already;//編碼后字符、shannon碼string get_text;
};shannon::shannon(string file_name){word.clear();get_text.clear();get_probability(file_name);make_code();
}int shannon::get_probability(string file_name){double word_amount = 0;double probability = 0;ifstream infile;ofstream outfile;map<char, double> word_count;infile.open(file_name, ios::in);if (!infile){cout << "can not open word text" << endl;return 0;}else{getline(infile, get_text);}for (auto &s : get_text){++word_count[s];++word_amount;}outfile.open("probability.txt", ios::out);for (auto &w : word_count){ostringstream stream;probability = w.second / word_amount;stream << w.first;outfile << stream.str() << "\t" << probability << endl;word.insert(make_pair(probability, stream.str()));already.insert(make_pair(stream.str(), ""));}return 1;
}int shannon::make_code(){double temp = 1.0;string code = "";int figures = 0;for (auto &w : word){temp -= w.first;figures = -(log(w.first) / log(2));code = decimals_to_binary(temp, figures);already.find(w.second)->second = code;}return 1;
}string shannon::decimals_to_binary(double decimals, int figures){string code = "";for (int i = 0; i < figures; ++i){decimals *= 2;ostringstream stream;stream << int(decimals);code += stream.str();if (decimals >= 1){decimals -= 1; }else{continue;}}return code;
}void shannon::show(){for (auto s : already){cout << s.first << "\t" << s.second << endl;}
}int main(){shannon a("demo.txt");a.show();system("pause");
}
總結(jié)
以上是生活随笔為你收集整理的shannon编码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。