#include<stdio.h>
#include <iostream>
#include <math.h>
#define N 100
using namespace std
double g(double x)
{
return (pow((x+1),1.0/3.0))
}
void main(void)
{
double x0
cout<<"初值为x0=:"
cin>>x0
int k,a=1,b=2
double x,x1,x2
while(k<N) //这里的k你没给初值
{
if(k==1)
x=g(x0)
else
{
x1=g(x0)
x2=g(x1)
x=(x0*x2-x1*x1)/(x0-2*x1+x2)
}
if((x0<1)||(x0>2))
{
cout<<"请另选初值:"<<endl
exit(0)
}
else
if((fabs(x-x0)>pow(10.0,-5))&&(fabs(x-x0)<pow(10.0,-4)))
{
cout<<"迭代成功:"<<endl
cout<<"迭代次数为:"<<k+1<<endl
cout<<"用简单迭代法解出此方程的近似解为:"<<x<<endl
break
}
else
{
k++
x0=x
}
}
if(k==N)
cout<<"迭代次数已经达到上界,不收敛。"<<endl
}
迭代法计算信道容量C++程序#include <iostream>
#include <vector>
#include <cfloat>
#include <cmath>
using namespace std
#define FLOAT_MINUS_PRECISION 0.00001
typedef vector<float*>VEC_PFLOAT
//迭代计算信道容量,参数值为信源,信宿符号个数和信道转移概率矩阵,返回信道容量
float GetCapacity(int nSourceSymbol,int nHostSymbol,const VEC_PFLOAT&vTransMatrix)
{
//信道容量初始化为最小值
float fCapacity = FLT_MIN
//信源概率分布
float *pfSoureProb = new float[nSourceSymbol]
//初始化信源分布为均匀分布
int i
for (i = 0i <nSourceSymboli++)
{
pfSoureProb[i] = 1.0 / nSourceSymbol
}
//初始化φ函数
VEC_PFLOAT vPhi
for (i = 0i <nSourceSymboli++)
{
float *pfTemp = new float[nHostSymbol]
vPhi.push_back(pfTemp)
}
//设置精度
const float cfDelta = 0.02f
float fPrecision
//迭代计算
int j,k
float *pfSum = new float[nSourceSymbol]
do
{
for (i = 0i <nSourceSymboli++)
{
for (j = 0j <nHostSymbolj++)
{
//计算ΣPi*Pji
float fSum = 0.0f
for (k = 0k <nSourceSymbolk++)
{
fSum += pfSoureProb[i] * vTransMatrix[k][i]
}
vPhi[i][j] = pfSoureProb[i] * vTransMatrix[j][i] / fSum
}
}
float fSumDeno = 0.0f //分母求和
for (i = 0i <nSourceSymboli++)
{
float fSum = 0.0f
for (j = 0j <nHostSymbolj++)
{
fSum += vTransMatrix[j][i] * logf(vPhi[i][j])
}
pfSum[i] = expf(fSum)
fSumDeno += pfSum[i]
}
for (i = 0i <nSourceSymboli++)
{
pfSoureProb[i] = pfSum[i] / fSumDeno
}
//计算新一轮的容量
float fNewC = logf(fSumDeno)
//计算精度
fPrecision = fabs(fNewC - fCapacity) / fCapacity
fCapacity = fNewC
} while(fPrecision - cfDelta >0.0f)
//释放临时资源...
delete []pfSum
for (i = 0i <vPhi.size()i++)
{
float* pfTemp = vPhi.at(i)
delete pfTemp
}
vPhi.clear()
return fCapacity
}
int main()
{
//转移矩阵
VEC_PFLOAT vTransMatrix
int nCol,nLine
cout<<"请输入信源符号个数:"
cin>>nLine
cout<<"请输入信宿符号个数:"
cin>>nCol
cout<<"请依次输入"<<"行信道转移概率矩阵:(以空格隔开每个概率)\n"
for (int i = 0i <nLinei++)
{
float *pfTemp = new float[nCol]
Label1:
float fSum = 0.0f
cout<<"X"<<":"
for (int j = 0j <nCol - 1j++)
{
cin>>pfTemp[j]
fSum += pfTemp[j]
}
if (1.0f - fSum <0)
{
cout<<"转移概率和应该为1,请重新输入!\n"
goto Label1
}
else
{
pfTemp[j] = 1.0f - fSum
cout<<"信源符号X"<<"的转移概率分别为:"
for(int k = 0k <nColk++)
cout<<pfTemp[k]
cout<<"\n"
}
vTransMatrix.push_back(pfTemp)
}
cout<<"信道容量为:"
for (int k = 0k <vTransMatrix.size()k++)
{
float* pfTemp = vTransMatrix.at(k)
delete pfTemp
}
vTransMatrix.clear()
return 0
}
看看对你有帮助吧!!!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)