ClearAll["Global`*"]
(*定义CDAC的基本信息*)
bits=10;vref=1;
(*创建CDAC的电容阵列*)
capArray=Join[Table[2^(bits-n),{n,2,bits,1}],{1}];
(*创建所有输出二进制编码数组*)
codes=Table[IntegerDigits[code,2,bits],{code,0,2^bits-1,1}];
(*创建Table存储每个code的每一次comp的能量E*)
codeLoopcompLoopE=Table[Table[0,bits],2^bits];

For[decCode=0,decCode<=2^bits-1,decCode++,
{code=codes[[decCode+1]];
For[cmpBit=1,cmpBit<=bits,cmpBit++,
{If[cmpBit<=1,
{posLastCode=Join[{0},Table[1,bits-1]];
posCurrentCode=Join[{0},Table[1,bits-1]];
negLastCode=Join[{0},Table[1,bits-1]];
negCurrentCode=Join[{0},Table[1,bits-1]]},
{}];
If[cmpBit>1,{posLastCode=posCurrentCode;negLastCode=negCurrentCode},{}];
If[cmpBit==2,{posCurrentCode[[1]]=If[code[[1]]==1,0,1];negCurrentCode[[1]]=If[code[[1]]==1,1,0]},{}];
If[cmpBit>2,
{posCurrentCode[[2;;cmpBit-1]]=Map[If[#==1,0,1]&,code[[2;;cmpBit-1]]];
negCurrentCode[[2;;cmpBit-1]]=Map[If[#==0,0,1]&,code[[2;;cmpBit-1]]]},
{}];


(*正向输入端CDAC电位状态 & VREF输出的电荷*)
posBotCodeChange=posCurrentCode-posLastCode;
posBotVoltageChangeArray=posBotCodeChange*vref;
(*总的电容是2^(bits-1)*)
posTopVoltageChange=Sum[(posBotCodeChange*capArray)[[i]],{i,1,bits}]/2^(bits-1);
posTopVoltageChangeArray=Table[posTopVoltageChange,bits];
posCurrentVrefCapArray=posCurrentCode*capArray;
posQ=Sum[(posCurrentVrefCapArray*(posBotVoltageChangeArray-posTopVoltageChangeArray))[[i]],{i,1,bits}];

(*负向输入端CDAC电位状态 & VREF输出的电荷*)
negBotCodeChange=negCurrentCode-negLastCode;
negBotVoltageChangeArray=negBotCodeChange*vref;
(*总的电容是2^(bits-1)*)
negTopVoltageChange=Sum[(negBotCodeChange*capArray)[[i]],{i,1,bits}]/2^(bits-1);
negTopVoltageChangeArray=Table[negTopVoltageChange,bits];
negCurrentVrefCapArray=negCurrentCode*capArray;
negQ=Sum[(negCurrentVrefCapArray*(negBotVoltageChangeArray-negTopVoltageChangeArray))[[i]],{i,1,bits}];

(*打印症状*)
(*Print["code=",code," comBit=",cmpBit," pos=",posLastCode,posCurrentCode,posQ," neg=",negLastCode,negCurrentCode,negQ];*)

(*单次CDAC提供的能量=电荷×VREF*)
codeLoopcompLoopE[[decCode+1,cmpBit]]=(posQ+negQ)*vref;
}];
}];

codeLoopcompLoopE;
codeLoopE=Map[Total[#]&,codeLoopcompLoopE];
codeLoop=Table[i,{i,0,2^bits-1}];
codeLoopVScodeLoopE=Transpose[{codeLoop,codeLoopE}];

Print["Average Energy=",Mean[codeLoopE]//N];
ListLinePlot[codeLoopVScodeLoopE,PlotRange->{{0,1024},{25,200}},Ticks->{Table[i,{i,0,1024,2^7}],Table[25*i,{i,1,20}]},GridLines->{Table[i,{i,0,1024,2^7}],Table[25*i,{i,1,20}]}]