Both languages in question (PHP and Node.JS, AKA Javascript) silently do

floating point arithmetic for you under certain conditions. The nature of

floating point arithmetic results in bad decimal results after multiple

successive operations due to rounding errors. In Javascript, all numbers

are actually doubles (64-bit floating point numbers), so all arithmetic

suffers this problem. In PHP, there is an integer type, but it's only 32

bits in length. Once an operation produces a value that is too big for an

integer, it is automatically converted into a 64-bit floating point value,

and thus starts accumulating error. As a result of the different points in

the operation that this happens, the magnitude of the error is different.

In Go, if you use a significantly large enough integer type (int64 will do

for this code), then all operations are done with integer math, and have no

rounding errors (and the whole thing is faster too!). If you use a float64

as the datatype, you get similar results to Javascript (which always uses

64-bit floats).

If you want to avoid the rounding, and all your operations are integer

operations, you can do the following:

1. Use an appropriately large enough fixed size integer.

2. If it's too big for your fixed size integers, you can use an

arbitrary precision integer (GO: math/big.Int, PHP: GMP, Javascript: None

built-in).

3. If that isn't an option then use a large floating point type (as

large as possible), and consider the result with a grain of salt.

Alternatively, if you use an algorithm that minimizes the number of

operations involved, then the number of rounding errors will be small, and

your result will be more accurate. In the case of the posted SO code, one

comment suggests using the formula "sum(1 to N) = (N/2)*(N+1)" which avoids

the loop, and only performs 3 floating point operations instead of 1

billion.

On Monday, August 12, 2013 11:34:04 AM UTC-7, andrey mirtchovski wrote:It would benefit the list if you took the time to compose your query

more clearly. As Jan remarks, the original link you provided explains

the issue very clearly: if you use integers with sufficient precision

to hold the full result you'll get the correct value. everything that

uses floats (including your example) gets the value deemed

"incorrect".

took me a few tries to sneak this under the "program took too long"

axe but now it should be cached:

http://play.golang.org/p/ajsglQCIjp --

You received this message because you are subscribed to the Google Groups "golang-nuts" group.

To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.

For more options, visit

https://groups.google.com/groups/opt_out.