Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FFI floats comparison #1216

Closed
Matrix89 opened this issue May 10, 2024 · 3 comments
Closed

FFI floats comparison #1216

Matrix89 opened this issue May 10, 2024 · 3 comments

Comments

@Matrix89
Copy link

It seems that when comparing two ffi floats only the integer part is checked eg. 0.1 and 0.5 are equal.

LuaJIT 2.1.1710088188 -- Copyright (C) 2005-2023 Mike Pall. https://luajit.org/
JIT: ON SSE3 SSE4.1 BMI2 fold cse dce fwd dse narrow loop abc sink fuse
> ffi = require("ffi")
> a = ffi.cast("float", 0.1)
> b = ffi.cast("float", 0.1)
> = a == b
true
> b = ffi.cast("float", 0.5)
> = a == b
true
> b = ffi.cast("float", 1)
> = a == b
false
>

Is this intentional or a quirk of how floats actually work?

@GitSparTV
Copy link

Does it work the same if you use ffi.new?

@Matrix89
Copy link
Author

Yep

LuaJIT 2.1.1713773202 -- Copyright (C) 2005-2023 Mike Pall. https://luajit.org/
JIT: ON SSE3 SSE4.1 BMI2 fold cse dce fwd dse narrow loop abc sink fuse
> ffi = require("ffi")
> a = ffi.new("float", 0.1)
> b = ffi.new("float", 0.2)
> = a == b
true
> b = ffi.new("float", 1)
> = a == b
false
>

BTW. I've only tested on x86

MikePall pushed a commit that referenced this issue May 25, 2024
Prevent misunderstandings like in #1216
@MikePall
Copy link
Member

Please never box scalar numbers with ffi.new("int"), ffi.new("float") or similar! This is only useful for passing arguments to vararg functions. Ditto for ffi.cast().

Explicitly boxing scalars does not improve performance or force int or float arithmetic. Or whatever the intention possibly was.

It just adds costly boxing, unboxing and conversions steps. And it may lead to surprise results, because cdata arithmetic on scalar numbers is always performed on 64 bit integers.

I've added this to the documentation. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants