# Tag Info

80

The undocumented GraphicsPolygonUtilsPointWindingNumber (if you're on versions < 10, use GraphicsMeshPointWindingNumber) does exactly this — it gives you the winding number of a point. A point lies inside the polygon if and only if its winding number is non-zero. Using this, you can create a Boolean function to test if a point is inside the polygon ...

51

Using the function winding from Heike's answer to a related question winding[poly_, pt_] := Round[(Total@ Mod[(# - RotateRight[#]) &@(ArcTan @@ (pt - #) & /@ poly), 2 Pi, -Pi]/2/Pi)] to modify the test function in this Wolfram Demonstration by R. Nowak to testpoint[poly_, pt_] := Round[(Total@ Mod[(# - RotateRight[#]) &@(ArcTan @@ (pt -...

33

You have several options: foo[arg_?(VectorQ[#,NumericQ]&)] foo[arg: {_?NumericQ ..}] foo[arg: {__?NumericQ}] For matrices or higher dimensional arrays, the equivalent of VectorQ is MatrixQ and ArrayQ. It's worth noting that VectorQ[..., NumericQ] (and its relatives MatrixQ and ArrayQ) are highly optimized and will avoid unpacking packed arrays: ...

28

As it happens there is a built-in function that already does this: Signature. If any two elements of list are the same, Signature[list] gives 0. dupeQ = 0 === Signature@# &; I believe this is the "canonical" answer. It is fast on both packed arrays and unpacked lists.

27

You could use MatrixRank. Here is a function that does this: eigenvectorQ[matrix_, vector_] := MatrixRank[{matrix . vector, vector}] == 1 For your example: eigenvectorQ[h, y] False

26

The second "Neat Example" in the documentation for SmoothKernelDistribution contains this compiled function: (* A region function for a bounding polygon using winding numbers: *) inPolyQ = Compile[{{polygon, _Real, 2}, {x, _Real}, {y, _Real}}, Block[{polySides = Length[polygon], X = polygon[[All, 1]], Y = polygon[[All, 2]], Xi, Yi, Yip1, wn = ...

26

Sometimes speed is an issue if there are many polygons and or many points to check. There is an excellent reference on this issue under http://erich.realtimerendering.com/ptinpoly/ with the main conclusion that the angle summation algorithm should be avoided if speed is the objective. Below is my Mathematica implementation of the point in polygon problem ...

26

Update: InternalRealValuedNumericQ /@ {1, N[Pi], 1/2, Sin[1.], Pi, 3/4, aa, I} (* {True, True, True, True, True, True, False, False} *) or InternalRealValuedNumberQ /@ {1, N[Pi], 1/2, Sin[1.], Pi, 3/4, aa, I} (* {True, True, True, True, False, True, False, False} *) Using @RM's test list listRM = With[{n = 10^5}, RandomSample[Flatten[{...

24

I usually use ToExpression["symbol", InputForm, ValueQ] ToExpression will wrap the result in its 3rd argument before evaluating it. Generally, all functions that extract parts (Extract, Level, etc.) have such an argument. This is useful when extracting parts of held expressions. ToExpression acts on strings or boxes, but both the problem with ...

24

Another approach to this problem is computing the winding number by integrating $1/z$ centered on the point of interest along the contour of the polygon in the complex plane. Sure this isn't exactly efficient, but still I think it's nice to see this working in action. And since complex integration is feasible in Mathematica, I just tried :) PointToComplex[{...

23

Note: I am not particularly knowledgable in the field of this question, so what I write below may well be wrong. I don't know whether or not this should be considered a bug, but to my mind this is an instance of a clash of programming and mathematical functionality. To put it differently, predicates (functions ending with Q) seem to be a wrong match for ...

22

You could use this package to triangulate your polygon, and then use this barycentric formula on each of the triangles. inside[{{x1_, y1_}, {x2_, y2_}, r3 : {x3_, y3_}}, r : {_, _}] := # >= 0 && #2 >= 0 && # + #2 < 1 & @@ LinearSolve[{{x1 - x3, x2 - x3}, {y1 - y3, y2 - y3}}, r - r3] Example for a single triangle: tri = {{...

22

Edit: It was pointed out that the original form is not bullet-proof, e.g. GraphicsPrimitiveQ /@ {InputNotebook, Unique, Sequence} all returned True. However, when looking upon this answer about generating new graphics primitives, a superior answer came to light: Clear[GraphicsPrimitiveQ]; GraphicsPrimitiveQ[s_Symbol | (s_)[___]] := 0 < Count[DownValues[...

22

VectorQ is specially optimized with the following functions The following were tested in M11.3 unless stated otherwise. Past versions may behave differently. NumberQ, NumericQ (verified in M10.0) MachineNumberQ IntegerQ DeveloperMachineRealQ, DeveloperMachineIntegerQ, DeveloperMachineComplexQ (verified in M10.0 but see bug below) Internal...

21

There is a RealQ, see DeveloperRealQ Also relevant: DeveloperMachineRealQ The difference between the two: DeveloperRealQ[1.20] DeveloperMachineRealQ[1.20] True False So, DeveloperRealQ is a test for arbitrary precision numbers, while DeveloperMachineRealQ checks whether its input is a double precision number. Notice that both return ...

20

As the responses show, there are a number of quick "probably real" tests. In general, the problem is undecidable, however. This is an easy corollary of Richardson's theorem, which says that it is impossible to decide if two real expressions $x$ and $y$ are equal. Assuming Richardson's theorem, note that $(x-y)i$ is real if and only if $x=y$. As a more ...

20

Others have argued in the comments that this behaviour makes sense mathematically, and I fully agree. But further than that, it is also very practical. Mathematica's functions are usually designed to give reasonable results for edge cases in the sense that if you put these functions together and write some more complex calculation, this compound function ...

18

You need to use === (or SameQ) instead of == (or Equal) to test the condition. This is because === always returns True or False, whereas == can remain unevaluated. For example: a === b (* False *) a == b (* a == b *) The fact that == remains unevaluated is why it is useful in Solve, Reduce and related functions, where you can write an expression such as a ...

18

From the Mathematica documentation for PolyhedronData (see Coordinate-related properties under "More information") RegionFunction – pure function giving True in the interior of the polyhedron. PolyhedronData["PentagonalDipyramid", "RegionFunction"] As I was playing around with this I noticed the Select part was very slow when running on lots of points, ...

17

Because the assumption system is not called during the standard evaluation sequence, it is only called when Simplify, FullSimplify, Sum, Integrate etc... are used. Thus, x>0 remains unevaluated: Assuming[x > 0, x > 0] (* ==> x > 0 *) and TrueQ then returns False: Assuming[x > 0, TrueQ[x > 0]] (* ==> False *) If, however, you run ...

17

Since someone dragged in Canada... Here is the code from a MathGroup post I had referenced. I have modified to compile to C and that speeds it further. The one-off preprocessing does take time but it seems not unreasonable. It takes a list of lists of polygons (so the "region" need not be connected). To account for this I slightly alter the setup from Mac's ...

17

As per Szabolcs's suggestion: Version 10 alternatives are RegionMember and Element, but the latter is unreasonably slow. A drop in alternative RegionMember[reg] returns a RegionMemberFunction[...] that can be applied repeatedly to different points. (* Memoizing the RegionMemberFunction[...] for a given polygon *) inPolyQHelper[poly_] := inPolyQHelper[...

16

If there are repeated elements in the list, then calling Union[] on it will shorten it so that this element only appears once, so a simple implementation would be to test these lengths: test[list_] := Length[Union[list]] != Length[list] If you wanted to know which elements where repeated, you this could be accomplished by using Gather[] to collect ...

16

There is in fact an easy test to determine if an integer is a power of $2$, thanks to bit twiddling: hadamardMatrix[1] := {{1}} hadamardMatrix[2] := {{1, 1}, {1, -1}} hadamardMatrix[n_Integer /; Positive[n] && BitAnd[n, n - 1] == 0] := KroneckerProduct[hadamardMatrix[2], hadamardMatrix[n/2]]

16

Unless both lists given to Equal are packed arrays Equal will first unpack. Unfortunately for this case {} is not a packable expression, therefore list == {} will always unpack list, assuming it starts packed. That unpacking takes time: test = RandomInteger[100000000, 10000000]; Developer`FromPackedArray[test]; // AbsoluteTiming {0.207012, Null} ...

15

RealQ[x_] := Element[x, Reals] === True It fulfills all your samples and I think is generally correct.

15

IF you can assume 1) they are integers, 2) they are ascending, and 3) no repeats, THEN your last idea should work Last[list]-First[list]==Length[list]-1 Or you could Union[Differences[list]]=={1} Without assumptions (2) and (3): Union[Differences[Sort[list]]]=={1}

15

Here's how this can be done: ClearAll[algebraicQ] algebraicQ[x_] := Module[{result}, result = Element[x, Algebraics]; result /; MatchQ[result, True | False]] The key to these types of problems is usually a special use of Condition inside Block/Module/With which allows sharing localized variables between the condition and the body of Module. At this ...

15

Why no RationalQ or RealQ? Probably because it isn't unambiguous what such a function should do. From the comments above: If there were a RationalQ, I'd expect RationalQ[2] to be False But many other users would expect something like this: For IntegerQ there aren't such conflicting expectations.

Only top voted, non community-wiki answers of a minimum length are eligible