Hi All,

I have a simple perl script which subtracts two variables holding decimal numbers and the results is not as expected.

$a = 417747646.853143
$b = 417747646.853142

$c = $a-$b

expected result = $0.000001
actual result = -9.5367431640625e-07

any idea on why I am getting wrong results?

There's a lot of literature on the limitations of floating-point arithmetic (google "floating point arithmetic" for a sample) so I won't try to replicate what smart people have already said well, but if you read down some of the stuff that's been written you'll get a pretty good idea. The article on "What Every Computer Scientist Should Know About Floating Point Arithmetic" is definitely worth reading, it'll tell you what you want to know.

Someone else might want to summarize this literature, but I haven't had my coffee yet, so I'll leave it to them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.