Extract float/double value
Here's the easy way. Don't use regex's for built-in types.
try:
x = float( someString )
except ValueError, e:
# someString was NOT floating-point, what now?
How to extract a floating number from a string
If your float is always expressed in decimal notation something like
>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4db.")
['13.4']
may suffice.
A more robust version would be:
>>> re.findall(r"[-+]?(?:\d*\.\d+|\d+)", "Current Level: -13.2db or 14.2 or 3")
['-13.2', '14.2', '3']
If you want to validate user input, you could alternatively also check for a float by stepping to it directly:
user_input = "Current Level: 1e100 db"
for token in user_input.split():
try:
# if this succeeds, you have your (first) float
print float(token), "is a float"
except ValueError:
print token, "is something else"
# => Would print ...
#
# Current is something else
# Level: is something else
# 1e+100 is a float
# db is something else
Swift extract an Int, Float or Double value from a String (type-conversion)
Convert String
to NSString
and Use convenience methods:
var str = "3.1"
To Int
var intValue : Int = NSString(string: str).integerValue
// 3
To Float
var floatValue : Float = NSString(string: str).floatValue
// 3.09999990463257
To Double
var doubleValue : Double = NSString(string: str).doubleValue
// 3.1
Reference
var doubleValue: Double { get }
var floatValue: Float { get }
var intValue: Int32 { get }
@availability(OSX, introduced=10.5)
var integerValue: Int { get }
@availability(OSX, introduced=10.5)
var longLongValue: Int64 { get }
@availability(OSX, introduced=10.5)
How to extract fractional part of a double value without rounding in c
How to extract fractional part of a double value without rounding ...?
Use modf()
from the standard C library.
#include <math.h>
double ipart;
double fraction = modf(value, &ipart);
printf("Fraction %g\n", fraction);
printf("Whole number %g\n", ipart);
The
modf
functions break the argument value into integral and fractional parts, each of which has the same type and sign as the argument. They store the integral part (in floating-point format) in the object pointed to by iptr.
C17dr § 7.12.6.12 2
Deeper into 8.2
double
can represent about 264 different values exactly. 8.2 is not one of them.
With double t = 8.2;
, t
takes on a nearby value, which is exactly 8.199999999999999289457264239899814128875732421875 or
81801439850948192/9007199254740992 due to the binary nature of common double
.
To find the fraction, use fraction*pow(2,DBL_MANT_DIG)/pow(2,DBL_MANT_DIG)
.
Thus the goal of "to get it as 200000 without rounding down" as 200000/denominator for the fraction part of t
is not possible.
Python: Extract multiple float numbers from string
You could also use regex to do this
import re
s = "38.00,SALE ,15.20"
p = re.compile(r'\d+\.\d+') # Compile a pattern to capture float values
floats = [float(i) for i in p.findall(s)] # Convert strings to float
print floats
Output:
[38.0, 15.2]
how to extract floating numbers from strings in javascript
You can use the regex /[+-]?\d+(\.\d+)?/g
in conjunction with String.match()
to parse the numbers and Array.map()
to turn them into floats:
var regex = /[+-]?\d+(\.\d+)?/g;
var str = '<tag value="20.434" value1="-12.334" />';
var floats = str.match(regex).map(function(v) { return parseFloat(v); });
console.log(floats);
var str2 = '20.434 -12.334';
var floats2 = str2.match(regex).map(function(v) { return parseFloat(v); });
console.log(floats2);
var strWithInt = "200px";
var ints = strWithInt.match(regex).map(function(v) { return parseFloat(v); });
console.log(ints);
See demo code here.
No insert and extract for float/double in SSE and AVX?
A scalar float/double is just the bottom element of an XMM/YMM register already, and there are various FP shuffle instructions including vinsertps
and vmovlhps
that can (in asm) do the insertion of a 32-bit or 64-bit element. There aren't versions of those which work on 256-bit YMM registers, though, and general 2-register shuffles aren't available until AVX-512, and only with a vector control.
Still much of the difficulty is in the intrinsics API, making it harder to get at the useful asm operations.
One not-bad way is to broadcast a scalar float or double and blend, partly because a broadcast is one of the ways that intrinsics already provide for getting a __m256d
that contains your scalar1.
Immediate-blend instructions can efficiently replace one element of another vector, even in the high half2. They have good throughput and latency, and back-end port distribution, on most AVX CPUs. They require SSE4.1, but with AVX they're always available.
(See also Agner Fog's VectorClass Library (VCL) for C++ templates for replacing an element of a vector; with various SSE / AVX feature levels. Including with runtime-variable index, but often designed to optimize down to something good for compile-time constants, e.g. a switch on the index like in Vec4f::insert()
)
float
into __m256
template <int pos>
__m256 insert_float(__m256 v, float x) {
__m256 xv = _mm256_set1_ps(x);
return _mm256_blend_ps(v, xv, 1<<pos);
}
The best case is with position=0. (Godbolt)
auto test2_merge_0(__m256 v, float x){
return insert_float<0>(v,x);
}
clang notices that the broadcast is redundant and optimizes it away:
test2_merge_0(float __vector(8), float):
vblendps ymm0, ymm0, ymm1, 1 # ymm0 = ymm1[0],ymm0[1,2,3,4,5,6,7]
ret
But clang gets too clever for its own good sometimes, and pessimizes this to
test2_merge_5(float __vector(8), float): # clang(trunk) -O3 -march=skylake
vextractf128 xmm2, ymm0, 1
vinsertps xmm1, xmm2, xmm1, 16 # xmm1 = xmm2[0],xmm1[0],xmm2[2,3]
vinsertf128 ymm0, ymm0, xmm1, 1
ret
Or when merging into a zeroed vector, clang uses vxorps
-zeroing and then a blend, but gcc does better:
test2_zero_0(float): # GCC(trunk) -O3 -march=skylake
vinsertps xmm0, xmm0, xmm0, 0xe
ret
Footnote 1:
Which is a problem for intrinsics; many intrinsics that you could use with a scalar float/double are only available with vector operands, and compilers don't always manage to optimize away _mm_set_ss
or _mm_set1_ps
or whatever when you only actually read the bottom element. A scalar float/double is either in memory or the bottom element of an X/YMM register already, so in asm it's 100% free to use vector shuffles on scalar floats / doubles that are already loaded into a register.
But there's no intrinsic to tell the compiler you want a vector with don't-care elements outside the bottom. This means you have to write your source in a way that looks like it's doing extra work, and rely on the compiler to optimize it away. How to merge a scalar into a vector without the compiler wasting an instruction zeroing upper elements? Design limitation in Intel's intrinsics?
Footnote 2:
Unlike vpinsrq
. As you can see from Godbolt, your version compiles very inefficiently, especially with GCC. They have to handle the high half of the __m256d
separately, although GCC finds way fewer optimizations and makes asm that's closer to your very inefficient code. BTW, make the function return
a __m256d
instead of assigning to a volatile
; that way you have less noise. https://godbolt.org/z/Wrn7n4soh)
_mm256_insert_epi64
is a "compound" intrinsic / helper function: vpinsrq
is only available in vpinsrq xmm, xmm, r/m64, imm8
form, which zero-extends the xmm register into the full Y/ZMM. Even clang's shuffle optimizer (which finds vmovlhps
to replace the high half of an XMM with the low half of another XMM) still ends up extracting and re-inserting the high half when you blend into an existing vector instead of zero.
The asm situation is that the scalar operand for extractps
is r/m32
, not an XMM register, so it's not useful for extracting a scalar float (except to store it to memory). See my answer on the Q&A Intel SSE: Why does `_mm_extract_ps` return `int` instead of `float`? for more about it and insertps
.
insertps xmm, xmm/m32, imm
can select a source float from another vector register, so the only intrinsic takes two vectors, leaving you with the How to merge a scalar into a vector without the compiler wasting an instruction zeroing upper elements? Design limitation in Intel's intrinsics? problem of convincing the compiler not to waste instructions setting elements in a __m128
when you only care about the bottom one.
Related Topics
Parse a .Py File, Read the Ast, Modify It, Then Write Back the Modified Source Code
How to Limit Memory Usage Within a Python Process
R Expand.Grid() Function in Python
How to Postpone/Defer the Evaluation of F-Strings
Error: Command 'Gcc' Failed with Exit Status 1 While Installing Eventlet
How to Remove Non-Ascii Characters But Leave Periods and Spaces
How to One-Hot-Encode from a Pandas Column Containing a List
Pandas Groupby Mean - into a Dataframe
Why Can Tuples Contain Mutable Items
Simple Way to Encode a String According to a Password
Change the Color of Text Within a Pandas Dataframe HTML Table Python Using Styles and CSS
How to Search Directories and Find Files That Match Regex
Creating Same Random Number Sequence in Python, Numpy and R
How to Make Separator in Pandas Read_CSV More Flexible Wrt Whitespace, for Irregular Separators
Scraping: Ssl: Certificate_Verify_Failed Error for Http://En.Wikipedia.Org