Hello Monks,
The business values I operated are floats; meanwhile the module I use to them in shared memory uses integers, that also guarantees the atomicity of writing int-values in shared memory.
Is there any way to pack (not convert) float to integer, without loosing precision? Way# 1
my $packed_integer = int($float * 1_000_000); my $unpacked_float = $packed_integer / 1_000_000;
Obviously, I loose precision here. In C I can do to manipulation with pointers, to get the result I like:
assert(sizeof(int) >= sizeof(float)); float f = ...; int *i_ptr = (int*)&f; int i = *int;
Then I've found can do something like that via pack/upack build-ins in Perl:
my $v = 1/3; my $v2 = unpack("F", pack("j", unpack("j", pack("F", $v)))); print ("v = $v\nv = $v2\n"); # v = 0.333333333333333 # v = 0.333333333333333
Seems fine.
?die("float cannot be packed into integer") unless ($int_size >= $float_size);
Thanks!
In reply to integer container for float by basiliscos
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |