تحويل تعويم لكثافة العمليات في F #

StackOverflow https://stackoverflow.com/questions/411221

  •  03-07-2019
  •  | 
  •  

سؤال

ويمكن للشخص يرجى توضيح لماذا int (0.4 * 10.0) هو 4 بعد int ((2.4 - 2.0) * 10.0) هو 3؟

وبعد ذلك أيضا يرجى شرح كيفية الحصول على 4. أي هل أنا حقا عليك القيام به int (System.Math.Round((2.4 - 2.0) * 10.0))؟

وانها مجرد قبيح جدا لشيء ينبغي أن يكون بهذه البساطة.

هل كانت مفيدة؟

المحلول

والتمثيل المزدوج لل2،4-2،0 هو ،399999999999. عند تحويل يتم اقتطاع عدد لكثافة العمليات الجزء العشري لذلك 3.999999999 يتم اقتطاع إلى 3.

نصائح أخرى

<اقتباس فقرة>   

وبعد ذلك أيضا يرجى شرح كيفية الحصول 4. أي هل أنا حقا عليك القيام به

     

والباحث (System.Math.Round ((2،4-2،0) * 10.0))

     

وانها مجرد قبيح جدا لشيء ينبغي أن يكون بهذه البساطة.

وبالطبع لا، مجرد تحديد

let round x = int System.Math.Round(x)

في الواقع، في صافي هناك نوع البيانات decimal التي سوف تساعدك مع هذه المشكلة، وإذا كان يمكن تمثيل الأرقام الخاصة بك تماما كما كسور عشرية.

2.4m - 2.0m == 0.4m
2.4 - 2.0   != 0.4

To covert a float number to an int use:

let i = Convert.ToInt32(f)

Floating-point numbers are not infinite precision. Some numbers can be represented perfectly (anything involving powers of two, e.g. 1, 1/2 = 0.5, 1/4 = 0.25, etc.), and others can't (e.g. 1/3 cannot be exactly decomposed into a finite sequence of powers of two). Often, chopping the end of the infinite series causes the encoded version of a number to be slightly smaller than its true value.

Combine this with the fact that the (int) operator truncates rather than rounds, and you can run into cases where an operation that should yield 4.0 results in 3.999999999991 instead, which becomes 3.

Any time you're trying to convert floats/doubles to ints, you want to think carefully about which operator you want to use -- truncating (rounding down), rounding up, or rounding-to-nearest.

Since this is an issue with floating-point representations, this is true not just in F#, but C# and (IIRC) Java and other languages.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top