算法中常常會到浮點數運算,而浮點數的處理常常是Verilog初學中常常遇到的問題。以下將就一個簡單的例子說明Verilog中浮點數運算處理。
在JPEG圖像壓縮時遇到色彩空間變換的問題,將YCbCr轉換到RGB會遇到浮點數的運算,這個實現復雜,以攝氏溫度轉換為華氏溫度為例 : F = C x 1.8 + 32
R = 1.164(Y-16) + 1.596(Cr-128)
G = 1.164(Y-16) - 0.391(Cb-128) - 0.813(Cr-128)
B = 1.164(Y-16) + 2.018(Cb-128)
module C2F( iclk,irstn,ic,of);
input iclk;
input irstn;
input[7:0] ic;
output[10:0] of;
reg[7:0] c;
reg[10:0] of;
always@(posedge iclk or negedge irstn)
begin
if(!irstn)
begin
c <= 0;
of <= 0;
end
else
begin
c <= ic;
of <= c * 1.8 + 32; // 直接處理,在ISE中綜合時會報出錯
end //ERROR:Xst:850 - "C2F.v" line 31: Unsupported real constant.
end
endmodule
以下為改正后的程序
module C2F( iclk,irstn,ic,of);
input iclk;
input irstn;
input[7:0] ic;
output[10:0] of;
reg[7:0] c;
reg[10:0] of;
reg[10:0] sum;
always@(posedge iclk or negedge irstn)
begin
if(!irstn)
begin
//c <= 0;
of <= 0;
sum <= 0;
end
else
begin
// c <= ic;
sum <= ic * 7+ 128;
of <= (sum >>2); //實際是 近似計算:of=(ic*7+128)/4=ic*1.75+32,
end
end
endmodule
http://blog.sina.com.cn/s/blog_6840802c0100ir5g.html
功能仿真:
在t1時刻,輸入ic=0x0B=11攝氏度,在iclk上升沿產生0x33=51華氏度
[ of=(11*7+128)/4=51.25華氏度 的近似 ,精確實際應為:11*1.8+32=51.8華氏度
其中t6時刻,輸入ic=16(0x10)(攝氏溫度16度), 在iclk上升沿計算:of=(16*7+128)/4=60(0x3C),
與精確計算 F = C x 1.8 + 32=16*1.8+32=60.8,即攝氏16度對應華氏60.8,存在計算誤差。