|
| 19 Nov 2014 11:40 PM |
print(2 == math.sqrt(2)^2) --> false print(2, math.sqrt(2)^2) --> 2 2
WTF????
-ForeverDev |
|
|
| Report Abuse |
|
|
DARPAUSA
|
  |
| Joined: 05 Jun 2014 |
| Total Posts: 11 |
|
|
| 20 Nov 2014 01:05 AM |
function is(a,b) return a==b; end; print(is(math.sqrt(2)*math.sqrt(2),2));
--> false
hmm, this is weird. |
|
|
| Report Abuse |
|
|
128GB
|
  |
| Joined: 17 Apr 2014 |
| Total Posts: 8056 |
|
|
| 20 Nov 2014 01:40 AM |
Its because its rounding the numbers
because the square root of 2 goes on forever, and lua (Obviously) isn't going to take it to the infinite'th digit
print(math.sqrt(2)) -->1.4142135623731, not the full number but as far as lua goes
print(1.4142135623731 ^ 2) -->2, but (1.4142135623731 ^ 2) is actually 2.00000000000001400410360361
the output is rounding it, math.sqrt(2) ^ 2 is more than 2 |
|
|
| Report Abuse |
|
|
128GB
|
  |
| Joined: 17 Apr 2014 |
| Total Posts: 8056 |
|
|
| 20 Nov 2014 01:43 AM |
also if you don't believe me print(2.00000000000001400410360361) -->2
it might have to do with print calling tostring on everything it prints before printing it
local a = tostring(2.00000000000001400410360361) print(#a) -->1 |
|
|
| Report Abuse |
|
|
eLunate
|
  |
| Joined: 29 Jul 2014 |
| Total Posts: 13268 |
|
|
| 20 Nov 2014 01:54 AM |
| There was similar stuff with using abs() and it messing up. The way to fix it was to explicitly cast it to a float or something |
|
|
| Report Abuse |
|
|
128GB
|
  |
| Joined: 17 Apr 2014 |
| Total Posts: 8056 |
|
|
| 20 Nov 2014 08:18 PM |
too bad you cant us sub on a number
local toString = tostring local function tostring(s) if type(s) == "number" then local r, c = "", 1 while s:sub(c, c) ~= "" do r = r .. s:sub(c, c) c = c + 1 end return r else return toString(s) end end |
|
|
| Report Abuse |
|
|
|
| 20 Nov 2014 08:23 PM |
Here is a solution:
local tolerance = 0.00001 local function is(n1, n2) return math.abs(n1 - n2) <= tolerance end
print(is(math.sqrt(2)*math.sqrt(2), 2)) -> true |
|
|
| Report Abuse |
|
|