Skip to content
Advertisement

SQL calculation for the sin() makes division by zero in one PosgreSQL function and don’t do it in another

There is a SQL call consisted of two general parts. The first one works, while the second one is commented out

select(2200 +
                        600 *
                                round(abs(sin(((1) * 0.042))) + 0.1) *
                                (sin(sin(((1) * 2 / 2 / 2.155172413793103 * PI()))) /
                                abs(sin(sin(((1) * 2 / 2 / 2.155172413793103* PI()))))) * --here is the division
                                (3 - exp(-12.5 + floor((1) * 2 / 2 / 2.155172413793103) * 2.155172413793103 * PI() * 2 * round(abs(sin(((1) * 0.042))) + 0.1) - (1 * 2 * PI())))
                        +
                        --600 *
                        --        abs(round(abs(sin(((1) * 0.042))) + 0.1) - 1) *
                        --        (sin(sin(((1) / 2 / 4.310344827586207 * PI()))) /
                        --        abs(sin(sin(((1) / 2 / 4.310344827586207 * PI()))))) * --here is the second division that causes the rpoblem
                        --        (3 - exp(-25.5 + floor((1) / 2 / 4.310344827586207) * 4.310344827586207 * PI() * 2 * abs(round(abs(sin(((1) * 0.042))) + 0.1) - 1) - (1 * PI())))
                        +50 * sin(3 + 1 * 0.092) + 350 * sin(3 + 1 * 0.012));

So, the question is why the

RROR:  division by zero
********** Error **********

ERROR: division by zero
SQL state: 22012

error occurs only if the second part is commented out. The part where the division occurs are all the same:

abs(sin(sin(((1) * 2 / 2 / 2.155172413793103 * PI()))))) *

vs

abs(sin(sin(((1) / 2 / 4.310344827586207 * PI()))))) *

they both should be zero, or none. But only the second one does throws the division by zero.

What is the root cause here and can I avoid that in the second state, is there a kind of type cas, or something else?

Advertisement

Answer

This is because there is difference in behaviour between integer division and float (decimal) division.

By following BODMAS rule:

Eg 1:

  1. (1) * 2 / 2 / 2.155172413793103
  2. 1 * 2 / 2 / 2.155172413793103
  3. 1 * 1/2.155172413793103
  4. 1 * 0.464
  5. 0.464

Eg 2:

  1. (1) / 2 / 4.310344827586207
  2. 1 / 2 / 4.310344827586207
  3. 0 / 4.310344827586207
  4. 0

So, 1/2 = 0 (integer division) and 1/2.0 = 0.5 (float division)

Even after correcting this error, the expressions will return different results because of BODMAS priority order followed by machines (Brackets Of Division Multiplication Addition Subtraction).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement