basiliscos has asked for the wisdom of the Perl Monks concerning the following question:
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: integer container for float
by BrowserUk (Patriarch) on Mar 28, 2016 at 11:38 UTC | |
|
Re: integer container for float
by syphilis (Archbishop) on Mar 28, 2016 at 12:44 UTC | |
by BrowserUk (Patriarch) on Mar 28, 2016 at 14:08 UTC | |
|
Re: integer container for float
by Anonymous Monk on Mar 28, 2016 at 16:22 UTC |