Why is 2 / -2 / 2 equal to -2 in OpenSCAD? (Mathematical Order of Operations)

4

1

Recently I have been doing more complicated math in OpenSCAD and I have run into something that I find strange. Take a simple math expression: 2 / 2 / 2. By any programming language this will equal 0.5 (1/2), and OpenSCAD agrees. Something like this: 2 / -2 / 2 should also be -0.5 for the same reason. However, OpenSCAD thinks this is -2. That is echo(2 / -2 / 2); gives ECHO: -2. My calculator, other programming languages (and myself) all say its -0.5.

Is this a quirk of OpenSCAD, or am I missing something obvious?

Elijah

Posted 2019-03-23T05:29:42.700

Reputation: 43

Check what (2 / -2) gets you – Trish – 2019-03-23T08:46:09.613

Answers

8

I suspect the behavior you are seeing is an undocumented feature (aka, bug) of OpenSCAD. I've found in the latest stable release that if the - is placed on either end, the result is -0.5, but in the middle, my results are the same as yours. Surrounding the -2 with parentheses results in a correct answer, however.

It appears that the parentheses turns a mathematical operation into a signed integer. It follows that the operations without the parentheses is right to left:

2/2 = 1, negative 1 with the minus, 2/-1 = -2

fred_dot_u

Posted 2019-03-23T05:29:42.700

Reputation: 8 399

2

Filed: https://github.com/openscad/openscad/issues/2894

– Joel Coehoorn – 2019-03-25T21:17:29.683

1

And there's now a fix for the issue merged into master. Nightly builds should handle this correctly from here on out.

– Joel Coehoorn – 2019-04-07T19:48:13.650

4

I filed this issue as a bug with the OpenSCAD project, and there is now a fix merged into master, as well as a test case to prevent regression. The latest nightly builds should handle this correctly from here on out.

Joel Coehoorn

Posted 2019-03-23T05:29:42.700

Reputation: 1 742