日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

shannon编码

發(fā)布時間:2023/12/8 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 shannon编码 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

shannon碼不是最佳編碼,是香農提出編碼理論后自己提出的一種編碼方式


shannon編碼主要分三個步驟

1.將字符按概率從大到小排序

2.將概率累加(除最小概率之外)

3.根據(jù)概率算出其信息熵確定碼長,根據(jù)碼長將其累加概率轉化為2進制碼即shannon碼


栗子:

碼字符:ABCD
概率:0.40.30.20.1
累加:00.40.70.9
碼:00011011110


// Shannon.cpp : 定義控制臺應用程序的入口點。 //#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進制小數(shù)轉2進制數(shù)(小數(shù),位數(shù))int get_probability(string file_name);//從文本中分析各個字符概率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"); }


總結

以上是生活随笔為你收集整理的shannon编码的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。