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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

关于浮点数计算时的精度问题

發(fā)布時(shí)間:2025/3/21 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 关于浮点数计算时的精度问题 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

那個(gè)有問題的縮略圖生成的方法發(fā)布之后,短短半天就有很多朋友響應(yīng),其中指出了不少方法中的不少問題,有些也是我沒有意識到的。果然集體的智慧是無窮的,一段代碼在許多人的眼皮底下經(jīng)過,想留有bug也不容易。不過,我在這里只能談一下我寫那篇文章的本意了,我認(rèn)為那篇文章中最主要的問題是,在計(jì)算圖片尺寸時(shí)沒有處理好浮點(diǎn)數(shù)計(jì)算的精度問題。

為了凸現(xiàn)主要邏輯,我把之前那個(gè)方法中計(jì)算圖片尺寸的代碼單獨(dú)抽取成一個(gè)方法:

public static void GetThumbnailSize(int originalWidth, int originalHeight,int desiredWidth, int desiredHeight,out int newWidth, out int newHeight) {// If the image is smaller than a thumbnail just return itif (originalWidth <= desiredWidth && originalHeight <= desiredHeight){newWidth = originalWidth;newHeight = originalHeight;return;}// scale down the smaller dimensionif ((decimal)desiredWidth / originalWidth < (decimal)desiredHeight / originalHeight){decimal desiredRatio = (decimal)desiredWidth / originalWidth;newWidth = desiredWidth;newHeight = (int)(originalHeight * desiredRatio);}else{decimal desiredRatio = (decimal)desiredHeight / originalHeight;newHeight = desiredHeight;newWidth = (int)(originalWidth * desiredRatio);} }

我們通過簡單的代碼試驗(yàn)一下:

int newWidth, newHeight;GetThumbnailSize(200, 200, 100, 100, out newWidth, out newHeight); Console.WriteLine("{0}, {1}", newWidth, newHeight);GetThumbnailSize(300, 300, 100, 100, out newWidth, out newHeight); Console.WriteLine("{0}, {1}", newWidth, newHeight);

得到的結(jié)果是:

100, 100 99, 100

第一個(gè)結(jié)果自然沒有問題,但是在第二個(gè)結(jié)果中為什么是99而不是100?為此,我們再通過以下的代碼來觀察一番:

ratio: 0.3333333333333333333333333333 new value: 99.99999999999999999999999999 to int: 99

可見,雖然使用了decimal,精度已經(jīng)非常高的,但是在經(jīng)過了一除一乘,它還是沒有恢復(fù)到最精確值。雖然一直說要注意浮點(diǎn)數(shù)計(jì)算時(shí)的精度問題,但是對于這個(gè)問題許多朋友往往只是理解到“不能直接兩個(gè)浮點(diǎn)數(shù)相等”,包括我自己的第一印象。但事實(shí)上,從上面的結(jié)果也可以看出,把一個(gè)浮點(diǎn)數(shù)直接轉(zhuǎn)換成整形,它便是使用了“去尾”而不是“四舍五入”的方法。因此,雖然newValue的值無比接近100,但是在強(qiáng)制去尾后它還是變成了99。

如果要在原來的方法中改變這個(gè)問題,最簡單的方法可能是把最后的強(qiáng)制轉(zhuǎn)型替換成Math.Round方法。Math.Round方法使用四舍五入,應(yīng)該能夠解決問題。不過如果只是這樣的話收獲不大,我們再仔細(xì)想想,應(yīng)該如何做到盡可能的精確。

兩個(gè)浮點(diǎn)數(shù)相除可能會喪失精度,但如果是乘法操作,在一般情況下精度是不會丟失的,除非發(fā)生了溢出的話,或者小數(shù)位數(shù)太多。因此在計(jì)算過程中為了保持精度,我們應(yīng)該盡可能的做乘法,而不是作除法。例如以下的判斷:

if ((decimal)desiredWidth / originalWidth < (decimal)desiredHeight / originalHeight)

其實(shí)最好改寫成“等價(jià)”的乘法操作(假設(shè)沒有溢出):

if (desiredWidth * originalHeight < desiredHeight * originalWidth)

同理,如果可以的話,在作計(jì)算的時(shí)候,也最好先乘再除:

if (desiredWidth * originalHeight < desiredHeight * originalWidth) {newWidth = desiredWidth;newHeight = (int)Math.Round((decimal)originalHeight * desiredWidth / originalWidth); } else {newHeight = desiredHeight;newWidth = (int)Math.Round((decimal)originalWidth * desiredHeight / originalHeight); }

這么做,我們就避免了使用scaleRatio這個(gè)已經(jīng)喪失部分精度的值來參與計(jì)算,這樣1 * 3 / 3便可以等于1,而不像1 / 3 * 3等于0.99…。因此,最終我們CreateThumbnail的代碼便修改為:

/// <summary> /// Creates a thumbnail from an existing image. Sets the biggest dimension of the /// thumbnail to either desiredWidth or Height and scales the other dimension down /// to preserve the aspect ratio /// </summary> /// <param name="imageStream">stream to create thumbnail for</param> /// <param name="desiredWidth">maximum desired width of thumbnail</param> /// <param name="desiredHeight">maximum desired height of thumbnail</param> /// <returns>Bitmap thumbnail</returns> public Bitmap CreateThumbnail(Bitmap originalBmp, int desiredWidth, int desiredHeight) {// If the image is smaller than a thumbnail just return itif (originalBmp.Width <= desiredWidth && originalBmp.Height <= desiredHeight){return originalBmp;}int newWidth, newHeight;// scale down the smaller dimensionif (desiredWidth * originalBmp.Height < desiredHeight * originalBmp.Width){newWidth = desiredWidth;newHeight = (int)Math.Round((decimal)originalBmp.Height * desiredWidth / originalBmp.Width);}else{newHeight = desiredHeight;newWidth = (int)Math.Round((decimal)originalBmp.Width * desiredHeight / originalBmp.Height);}// This code creates cleaner (though bigger) thumbnails and properly// and handles GIF files better by generating a white background for// transparent images (as opposed to black)// This is preferred to calling Bitmap.GetThumbnailImage()Bitmap bmpOut = new Bitmap(newWidth, newHeight);using (Graphics graphics = Graphics.FromImage(bmpOut)){graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;graphics.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);graphics.DrawImage(originalBmp, 0, 0, newWidth, newHeight);}return bmpOut; }

當(dāng)然,在前文中很多朋友指出的其他一些問題也很有道理,例如:

  • 沒有做參數(shù)校驗(yàn)。
  • 直接返回源圖片的做法讓方法的含義不同。
  • 經(jīng)過計(jì)算后newWidth和newHeight可能為0。

例如還有朋友提出對GIF的處理不很妥當(dāng)?shù)鹊取绻衅渌敕ǖ脑?#xff0c;也可以繼續(xù)討論。或者,你也來分享一下代碼或工作中發(fā)現(xiàn)的問題?

from:?http://blog.zhaojie.me/2009/11/precision-of-float-point-calculation.html

總結(jié)

以上是生活随笔為你收集整理的关于浮点数计算时的精度问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

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