Python math.h() Examples
The following are 30
code examples of math.h().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
math
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: test_verify.py From SwiftKitten with MIT License | 6 votes |
def test_FILE_stored_explicitly(): ffi = FFI() ffi.cdef("int myprintf11(const char *, int); FILE *myfile;") lib = ffi.verify(""" #include <stdio.h> FILE *myfile; int myprintf11(const char *out, int value) { return fprintf(myfile, out, value); } """) import os fdr, fdw = os.pipe() fw1 = os.fdopen(fdw, 'wb', 256) lib.myfile = ffi.cast("FILE *", fw1) # fw1.write(b"X") r = lib.myprintf11(b"hello, %d!\n", ffi.cast("int", 42)) fw1.close() assert r == len("hello, 42!\n") # result = os.read(fdr, 256) os.close(fdr) # the 'X' might remain in the user-level buffer of 'fw1' and # end up showing up after the 'hello, 42!\n' assert result == b"Xhello, 42!\n" or result == b"hello, 42!\nX"
Example #2
Source File: test_verify1.py From SwiftKitten with MIT License | 6 votes |
def test_opaque_integer_as_function_result(): #import platform #if platform.machine().startswith('sparc'): # py.test.skip('Breaks horribly on sparc (SIGILL + corrupted stack)') #elif platform.machine() == 'mips64' and sys.maxsize > 2**32: # py.test.skip('Segfaults on mips64el') # XXX bad abuse of "struct { ...; }". It only works a bit by chance # anyway. XXX think about something better :-( ffi = FFI() ffi.cdef(""" typedef struct { ...; } myhandle_t; myhandle_t foo(void); """) lib = ffi.verify(""" typedef short myhandle_t; myhandle_t foo(void) { return 42; } """) h = lib.foo() assert ffi.sizeof(h) == ffi.sizeof("short")
Example #3
Source File: test_verify.py From SwiftKitten with MIT License | 6 votes |
def test_opaque_integer_as_function_result(): #import platform #if platform.machine().startswith('sparc'): # py.test.skip('Breaks horribly on sparc (SIGILL + corrupted stack)') #elif platform.machine() == 'mips64' and sys.maxsize > 2**32: # py.test.skip('Segfaults on mips64el') # XXX bad abuse of "struct { ...; }". It only works a bit by chance # anyway. XXX think about something better :-( ffi = FFI() ffi.cdef(""" typedef struct { ...; } myhandle_t; myhandle_t foo(void); """) lib = ffi.verify(""" typedef short myhandle_t; myhandle_t foo(void) { return 42; } """) h = lib.foo() assert ffi.sizeof(h) == ffi.sizeof("short")
Example #4
Source File: test_verify1.py From SwiftKitten with MIT License | 6 votes |
def test_FILE_stored_explicitly(): ffi = FFI() ffi.cdef("int myprintf11(const char *, int); FILE *myfile;") lib = ffi.verify(""" #include <stdio.h> FILE *myfile; int myprintf11(const char *out, int value) { return fprintf(myfile, out, value); } """) import os fdr, fdw = os.pipe() fw1 = os.fdopen(fdw, 'wb', 256) lib.myfile = ffi.cast("FILE *", fw1) # fw1.write(b"X") r = lib.myprintf11(b"hello, %d!\n", ffi.cast("int", 42)) fw1.close() assert r == len("hello, 42!\n") # result = os.read(fdr, 256) os.close(fdr) # the 'X' might remain in the user-level buffer of 'fw1' and # end up showing up after the 'hello, 42!\n' assert result == b"Xhello, 42!\n" or result == b"hello, 42!\nX"
Example #5
Source File: test_verify1.py From SwiftKitten with MIT License | 6 votes |
def test_errno_working_even_with_pypys_jit(): ffi = FFI() ffi.cdef("int f(int);") lib = ffi.verify(""" #include <errno.h> int f(int x) { return (errno = errno + x); } """) @_run_in_multiple_threads def test1(): ffi.errno = 0 for i in range(10000): e = lib.f(1) assert e == i + 1 assert ffi.errno == e for i in range(10000): ffi.errno = i e = lib.f(42) assert e == i + 42
Example #6
Source File: test_verify.py From SwiftKitten with MIT License | 6 votes |
def test_take_and_return_partial_structs(): ffi = FFI() ffi.cdef(""" typedef struct { int x; ...; } foo_t; foo_t foo(foo_t, foo_t); """) lib = ffi.verify(""" typedef struct { int y, x; } foo_t; foo_t foo(foo_t a, foo_t b) { foo_t r = { 100, a.x * 5 + b.x * 7 }; return r; } """) args = ffi.new("foo_t[3]") args[0].x = 1000 args[2].x = -498 h = lib.foo(args[0], args[2]) assert ffi.sizeof(h) == 2 * ffi.sizeof("int") assert h.x == 1000 * 5 - 498 * 7
Example #7
Source File: test_zdistutils.py From SwiftKitten with MIT License | 6 votes |
def test_extension_object(self): ffi = FFI() ffi.cdef("double sin(double x);") csrc = '/*7%s*/' % self + ''' #include <math.h> #ifndef TEST_EXTENSION_OBJECT # error "define_macros missing" #endif ''' lib = ffi.verify(csrc, define_macros=[('TEST_EXTENSION_OBJECT', '1')], force_generic_engine=self.generic, libraries=[self.lib_m]) assert lib.sin(12.3) == math.sin(12.3) v = ffi.verifier ext = v.get_extension() assert 'distutils.extension.Extension' in str(ext.__class__) or \ 'setuptools.extension.Extension' in str(ext.__class__) assert ext.sources == [maybe_relative_path(v.sourcefilename)] assert ext.name == v.get_module_name() assert ext.define_macros == [('TEST_EXTENSION_OBJECT', '1')]
Example #8
Source File: test_recompiler.py From SwiftKitten with MIT License | 6 votes |
def test_unicode_libraries(): try: unicode except NameError: py.test.skip("for python 2.x") # import math lib_m = "m" if sys.platform == 'win32': #there is a small chance this fails on Mingw via environ $CC import distutils.ccompiler if distutils.ccompiler.get_default_compiler() == 'msvc': lib_m = 'msvcrt' ffi = FFI() ffi.cdef(unicode("float sin(double); double cos(double);")) lib = verify(ffi, 'test_math_sin_unicode', unicode('#include <math.h>'), libraries=[unicode(lib_m)]) assert lib.cos(1.43) == math.cos(1.43)
Example #9
Source File: test_verify.py From SwiftKitten with MIT License | 6 votes |
def test_ptr_to_opaque(): ffi = FFI() ffi.cdef("typedef ... foo_t; int f1(foo_t*); foo_t *f2(int);") lib = ffi.verify(""" #include <stdlib.h> typedef struct { int x; } foo_t; int f1(foo_t* p) { int x = p->x; free(p); return x; } foo_t *f2(int x) { foo_t *p = malloc(sizeof(foo_t)); p->x = x; return p; } """) p = lib.f2(42) x = lib.f1(p) assert x == 42
Example #10
Source File: test_verify.py From SwiftKitten with MIT License | 6 votes |
def test_implicit_unicode_on_windows(): if sys.platform != 'win32': py.test.skip("win32-only test") ffi = FFI() e = py.test.raises(FFIError, ffi.cdef, "int foo(LPTSTR);") assert str(e.value) == ("The Windows type 'LPTSTR' is only available after" " you call ffi.set_unicode()") for with_unicode in [True, False]: ffi = FFI() ffi.set_unicode(with_unicode) ffi.cdef(""" DWORD GetModuleFileName(HMODULE hModule, LPTSTR lpFilename, DWORD nSize); """) lib = ffi.verify(""" #include <windows.h> """, libraries=['Kernel32']) outbuf = ffi.new("TCHAR[]", 200) n = lib.GetModuleFileName(ffi.NULL, outbuf, 500) assert 0 < n < 500 for i in range(n): #print repr(outbuf[i]) assert ord(outbuf[i]) != 0 assert ord(outbuf[n]) == 0 assert ord(outbuf[0]) < 128 # should be a letter, or '\'
Example #11
Source File: testsuite.py From ctypesgen with BSD 2-Clause "Simplified" License | 6 votes |
def setUp(self): """NOTE this is called once for each test* method (it is not called once per class). FIXME This is slightly inefficient as it is called *way* more times than it needs to be. """ header_str = """ #include <math.h> #define sin_plus_y(x,y) (sin(x) + (y)) """ if sys.platform == "win32": # pick something from %windir%\system32\msvc*dll that include stdlib libraries = ["msvcrt.dll"] libraries = ["msvcrt"] elif sys.platform.startswith("linux"): libraries = ["libm.so.6"] else: libraries = ["libc"] self.module, output = ctypesgentest.test(header_str, libraries=libraries, all_headers=True)
Example #12
Source File: test_fallback_expressions.py From m2cgen with MIT License | 6 votes |
def test_abs_fallback_expr(): expr = ast.AbsExpr(ast.NumVal(-2.0)) interpreter = CInterpreter() interpreter.abs_function_name = NotImplemented expected_code = """ #include <math.h> double score(double * input) { double var0; double var1; var1 = -2.0; if ((var1) < (0)) { var0 = (0.0) - (var1); } else { var0 = var1; } return var0; } """ assert_code_equal(interpreter.interpret(expr), expected_code)
Example #13
Source File: testsuite.py From ctypesgen with BSD 2-Clause "Simplified" License | 5 votes |
def cleanup_json_src_paths(json): """ JSON stores the path to some source items. These need to be genericized in order for tests to succeed on all machines/user accounts. """ TYPES_W_PATHS = ["CtypesStruct", "CtypesEnum"] for i in json: if "ctype" in i and i["ctype"]["Klass"] in TYPES_W_PATHS: i["ctype"]["src"][0] = "/some-path/temp.h"
Example #14
Source File: mathematics.py From PyChemia with MIT License | 5 votes |
def rotation_matrix_weave(axis, theta, mat=None): try: from scipy import weave except ImportError: raise NotImplementedError if mat is None: mat = np.eye(3, 3) support = "#include <math.h>" code = """ double x = sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]); double a = cos(theta / 2.0); double b = -(axis[0] / x) * sin(theta / 2.0); double c = -(axis[1] / x) * sin(theta / 2.0); double d = -(axis[2] / x) * sin(theta / 2.0); mat[0] = a*a + b*b - c*c - d*d; mat[1] = 2 * (b*c - a*d); mat[2] = 2 * (b*d + a*c); mat[3*1 + 0] = 2*(b*c+a*d); mat[3*1 + 1] = a*a+c*c-b*b-d*d; mat[3*1 + 2] = 2*(c*d-a*b); mat[3*2 + 0] = 2*(b*d-a*c); mat[3*2 + 1] = 2*(c*d+a*b); mat[3*2 + 2] = a*a+d*d-b*b-c*c; """ weave.inline(code, ['axis', 'theta', 'mat'], support_code=support, libraries=['m']) return mat
Example #15
Source File: test_verify1.py From SwiftKitten with MIT License | 5 votes |
def test_strlen_array_of_char(): ffi = FFI() ffi.cdef("size_t strlen(char[]);") lib = ffi.verify("#include <string.h>") assert lib.strlen(b"hello") == 5
Example #16
Source File: testsuite.py From ctypesgen with BSD 2-Clause "Simplified" License | 5 votes |
def setUp(self): """NOTE this is called once for each test* method (it is not called once per class). FIXME This is slightly inefficient as it is called *way* more times than it needs to be. """ header_str = "#include <stdlib.h>\n" if sys.platform == "win32": # pick something from %windir%\system32\msvc*dll that include stdlib libraries = ["msvcrt.dll"] libraries = ["msvcrt"] elif sys.platform.startswith("linux"): libraries = ["libc.so.6"] else: libraries = ["libc"] self.module, output = ctypesgentest.test(header_str, libraries=libraries, all_headers=True)
Example #17
Source File: basic.py From attention-lvcsr with MIT License | 5 votes |
def c_headers(self, c_compiler): l = ['<math.h>'] # These includes are needed by Scalar and TensorType, # we declare them here and they will be re-used by TensorType l.append('<numpy/arrayobject.h>') l.append('<numpy/arrayscalars.h>') if config.lib.amdlibm and c_compiler.supports_amdlibm: l += ['<amdlibm.h>'] return l
Example #18
Source File: testsuite.py From ctypesgen with BSD 2-Clause "Simplified" License | 5 votes |
def setUp(self): """NOTE this is called once for each test* method (it is not called once per class). FIXME This is slightly inefficient as it is called *way* more times than it needs to be. """ header_str = """ #include <stdbool.h> struct foo { bool is_bar; int a; }; """ self.module, _ = ctypesgentest.test(header_str) # , all_headers=True)
Example #19
Source File: basic.py From D-VAE with MIT License | 5 votes |
def c_headers(self, c_compiler): l = ['<math.h>'] # These includes are needed by Scalar and TensorType, # we declare them here and they will be re-used by TensorType l.append('<numpy/arrayobject.h>') l.append('<numpy/arrayscalars.h>') if config.lib.amdlibm and c_compiler.supports_amdlibm: l += ['<amdlibm.h>'] return l
Example #20
Source File: test_recompiler.py From SwiftKitten with MIT License | 5 votes |
def test_math_sin_type(): ffi = FFI() ffi.cdef("double sin(double);") lib = verify(ffi, 'test_math_sin_type', '#include <math.h>') # 'lib.sin' is typed as a <built-in method> object on lib assert ffi.typeof(lib.sin).cname == "double(*)(double)" # 'x' is another <built-in method> object on lib, made very indirectly x = type(lib).__dir__.__get__(lib) py.test.raises(TypeError, ffi.typeof, x) # # present on built-in functions on CPython; must be emulated on PyPy: assert lib.sin.__name__ == 'sin' assert lib.sin.__module__ == '_CFFI_test_math_sin_type' assert lib.sin.__doc__ == 'direct call to the C function of the same name'
Example #21
Source File: testsuite.py From ctypesgen with BSD 2-Clause "Simplified" License | 5 votes |
def test_help(self): """Test that script at least generates a help""" o, e, c = self._exec(["--help"]) self.assertEqual(c, 0) self.assertEqual( o.decode().splitlines()[0], "Usage: run.py [options] /path/to/header.h ..." ) self.assertGreater(len(o), 3000) # its long, so it must be the generated help self.assertEqual(e.decode(), "")
Example #22
Source File: test_verify1.py From SwiftKitten with MIT License | 5 votes |
def test_array_as_argument(): ffi = FFI() ffi.cdef(""" size_t strlen(char string[]); """) ffi.verify("#include <string.h>")
Example #23
Source File: test_verify1.py From SwiftKitten with MIT License | 5 votes |
def test_func_as_argument(): ffi = FFI() ffi.cdef(""" void qsort(void *base, size_t nel, size_t width, int compar(const void *, const void *)); """) ffi.verify("#include <stdlib.h>")
Example #24
Source File: test_verify1.py From SwiftKitten with MIT License | 5 votes |
def test_longdouble(): ffi = FFI() ffi.cdef("long double sinl(long double x);") lib = ffi.verify('#include <math.h>', libraries=lib_m) for input in [1.23, ffi.cast("double", 1.23), ffi.cast("long double", 1.23)]: x = lib.sinl(input) assert repr(x).startswith("<cdata 'long double'") assert (float(x) - math.sin(1.23)) < 1E-10
Example #25
Source File: test_verify1.py From SwiftKitten with MIT License | 5 votes |
def test_relative_to(): py.test.skip("not available") import tempfile, os from testing.udir import udir tmpdir = tempfile.mkdtemp(dir=str(udir)) ffi = FFI() ffi.cdef("int foo(int);") f = open(os.path.join(tmpdir, 'foo.h'), 'w') f.write("int foo(int a) { return a + 42; }\n") f.close() lib = ffi.verify('#include "foo.h"', include_dirs=['.'], relative_to=os.path.join(tmpdir, 'x')) assert lib.foo(100) == 142
Example #26
Source File: test_verify1.py From SwiftKitten with MIT License | 5 votes |
def test_strlen_approximate(): lib = _Wconversion("int strlen(char *s);", "#include <string.h>") assert lib.strlen(b"hi there!") == 9
Example #27
Source File: test_verify1.py From SwiftKitten with MIT License | 5 votes |
def test_strlen_exact(): ffi = FFI() ffi.cdef("size_t strlen(const char *s);") lib = ffi.verify("#include <string.h>") assert lib.strlen(b"hi there!") == 9
Example #28
Source File: test_verify1.py From SwiftKitten with MIT License | 5 votes |
def test_rounding_2(): ffi = FFI() ffi.cdef("double sin(float x);") lib = ffi.verify('#include <math.h>', libraries=lib_m) res = lib.sin(1.23) assert res != math.sin(1.23) # not exact, because of double->float assert abs(res - math.sin(1.23)) < 1E-5
Example #29
Source File: test_verify1.py From SwiftKitten with MIT License | 5 votes |
def test_Wconversion_double2int(): _Wconversion("int sin(double);", "#include <math.h>", libraries=lib_m)
Example #30
Source File: test_verify1.py From SwiftKitten with MIT License | 5 votes |
def test_Wconversion_float2int(): _Wconversion("int sinf(float);", "#include <math.h>", libraries=lib_m)