What is the difference between int() and floor() in Python 3?

floor() rounds down. int() truncates. The difference is clear when you use negative numbers: >>> import math >>> math.floor(-3.5) -4 >>> int(-3.5) -3 Rounding down on negative numbers means that they move away from 0, truncating moves them closer to 0. Putting it differently, the floor() is always going to be lower or equal to … Read more

How to round a floating point number up to a certain decimal place?

8.833333333339 (or 8.833333333333334, the result of 106.00/12) properly rounded to two decimal places is 8.83. Mathematically it sounds like what you want is a ceiling function. The one in Python’s math module is named ceil: import math v = 8.8333333333333339 print(math.ceil(v*100)/100) # -> 8.84 Respectively, the floor and ceiling functions generally map a real number … Read more

Binary representation of float in Python (bits not hex)

You can do that with the struct package: import struct def binary(num): return ”.join(‘{:0>8b}’.format(c) for c in struct.pack(‘!f’, num)) That packs it as a network byte-ordered float, and then converts each of the resulting bytes into an 8-bit binary representation and concatenates them out: >>> binary(1) ‘00111111100000000000000000000000’ Edit: There was a request to expand the … Read more

How can I improve performance via a high-level approach when implementing long equations in C++

Edit summary My original answer merely noted that the code contained a lot of replicated computations and that many of the powers involved factors of 1/3. For example, pow(x, 0.1e1/0.3e1) is the same as cbrt(x). My second edit was just wrong, and and my third extrapolated on this wrongness. This is what makes people afraid … Read more

PHP – Floating Number Precision [duplicate]

Because floating point arithmetic != real number arithmetic. An illustration of the difference due to imprecision is, for some floats a and b, (a+b)-b != a. This applies to any language using floats. Since floating point are binary numbers with finite precision, there’s a finite amount of representable numbers, which leads accuracy problems and surprises … Read more

Converting a number with comma as decimal point to float

Using str_replace() to remove the dots is not overkill. $string_number=”1.512.523,55″; // NOTE: You don’t really have to use floatval() here, it’s just to prove that it’s a legitimate float value. $number = floatval(str_replace(‘,’, ‘.’, str_replace(‘.’, ”, $string_number))); // At this point, $number is a “natural” float. print $number; This is almost certainly the least CPU-intensive … Read more