Hot answers tagged

57

There are already good answers, but I'm going to improve the performance, generalize to any region in any dimensions and make the function more convenient. The main idea is to use DirichletDistribution (the uniform distribution on a simplex, e.g. triangle or tetrahedron). This idea was implemented by PlatoManiac and me in the related question obtaining ...


45

This is based on Rahul's ideas, but a different implementation: contourRegionPlot3D[region_, {x_, x0_, x1_}, {y_, y0_, y1_}, {z_, z0_, z1_}, opts : OptionsPattern[]] := Module[{reg, preds}, reg = LogicalExpand[region && x0 <= x <= x1 && y0 <= y <= y1 && z0 <= z <= z1]; preds = Union@Cases[reg, _Greater | ...


42

Update: Extended to Include 3D Shapes I have extended the workflow to include using 3D shapes including an imported 3D CAD object at the end of this answer. Original Post Here is a slight adaptation to my answer to your previous question here. It uses region functions, but not RegionIntersection. Rather it relies on the ray advancing to within the ...


37

EDIT 01: The original code had an issue when the angle of the ray is counterclockwise from the normal of the circle, which I didn't catch. The code should be correct now, I think. RegionIntersection and friends are really nice functions if you just need to find a couple of values, but it looks to me like RegionIntersection will be called 500 times (since ...


35

This assumes uniform distribution. See answer by @JimBaldwin for discussion on limitations (implicit assumptions) of my answer. Answer region = ImplicitRegion[0.5 < q < 1. && 0.5 < p < 0.5/q, {p, q}]; RandomPoint[region] (* {0.793318, 0.550934} *) Visual Show[ RegionPlot[region] , ListPlot[RandomPoint[region, 1000], PlotStyle -> ...


32

Metropolis algorithm Update: ~15x speedup with Compile! I propose an original solution, which consists in using the Metropolis algorithm. It is a very general approach, which is applicable for any probability density function in any dimensions. Metropolis /: Random`DistributionVector[ Metropolis[pdf_, u0_, s_: 1, n0_: 100, chains_: 200], n_Integer, ...


30

Assuming polygons follow the same (clockwise or counterclockwise) vertex order, find all good quality two line segment rigid mappings between polygons without overlap with each other (at least much overlap, that is). Construct a graph of these mappings and apply appropriate transforms to polygons by finding transform paths from one polygon to all others. (In ...


28

The question does not state an essential piece of information which is the joint distribution of $p$ and $q$. All of the previous answers (so far) jump to a solution without making the joint distribution explicit (at least prior to what one sees in the code and the resulting figures). The answers using regions assume that $p$ and $q$ have uniform ...


27

Good news! Version 10.2 of Mathematica has this built-in with the function RandomPoint[]. From the documentation: RandomPoint can generate random points for any RegionQ region that is also ConstantRegionQ. RandomPoint will generate points uniformly in the region reg. The first example given is a simple disk, but there are a whole host of neat ...


27

UPDATE: The previous version of my answer worked, but did not give control on the rounding radius, nor did it fully work with as a starting point for a geometric region for further calculations. Here is a version that is still based on spline curves, but it gives full control over the corner rounding radius. It also returns a FilledCurve object that in my ...


26

Lets call your plot res. res = RegionPlot[And @@ Table[ Dot[{Phi1, Phi2}, Eta[b]] <= Norm[NI[Pi] - Eta[b]]^2 + 2, {b, 0, 2 Pi, 2 Pi/10}], {Phi1, -7, 7}, {Phi2, -7, 7}]; Lets extract the mesh Mathematica is generating by default. Use more PlotPoints to get more triangular mesh of your 2D region. pts = res[[1, 1]]; (* Vertices *) {triangles, qd} = ...


24

You can always hide away the coordinate transformations inside a function that calls RegionPlot3D. Here's a quick & dirty sphericalRegionPlot3D: sphericalRegionPlot3D[ ineq_, {r_, rmin_: 0, rmax_: 1}, {th_, thmin_: 0, thmax_}, {ph_, phmin_, phmax_}, opts___] := RegionPlot3D[With[{ r = Sqrt[x^2 + y^2 + z^2], th = ArcCos[z/Sqrt[x^2 + y^2 + ...


23

Update 2: Finally ... in version 12.1 you can use the new directives HatchFilling and PatternFilling: Graphics[{EdgeForm[{Thick, Black}], #, blob}, ImageSize -> 300] & /@ {HatchFilling[], Directive[Red, HatchFilling[Pi/2, 2, 10]]} // Row Graphics[{EdgeForm[{Thick, Black}], PatternFilling[#, ImageScaled[1/20]], blob}, ImageSize -> 300] &...


23

If I'm not mistaken, a complement is defined as the set of elements in one set that are not contained in a given other set. In your case, you have specified the 'other' set (the union of S1, S2 and S3), but not the 'one' set. As you phrased it, I guess that set must be $\mathbb R^3$. So, the complement is the difference between an infinite space and a finite ...


23

Interpolation error The overshoots are the unavoidable result of interpolation. NDSolve computes the values of u of the DirichletCondition to machine-precision accuracy and approximates the values of u at other points in the mesh via the finite element method. Values at intermediate points are interpolated by polynomials that equal the values of u at the ...


22

For a different approach with image processing, I start with the image of your puzzle. fig = Import["http://i.stack.imgur.com/xpue6m.jpg"]; comp = MorphologicalComponents[fig // Binarize]; comp = Colorize[comp, ColorFunction -> "Rainbow"]; cols = DominantColors[comp, 20]; blocks = ColorNegate[Binarize@ColorReplace[comp, Cases[cols, Except[cols[[#...


22

I suspect the problem arises from too coarse a mesh when the Disk region is discretized. A better result is obtained if the region is created explicitly with a finer mesh at the edge. region = DiscretizeRegion[Disk[], MeshRefinementFunction -> Function[{vertices, area}, area > 0.005 (1 - Norm[Mean[vertices]]^2)]] sol = NDSolveValue[{-...


20

You can use Show to combine graphics of the same type: g1 = Plot3D[x^2 - y^2, {x, -3, 3}, {y, -3, 3}, RegionFunction -> Function[{x, y, z}, 2 < x^2 + y^2 < 9]]; g2 = SphericalPlot3D[ 1 + Sin[5 θ] Sin[5 φ]/5, {θ, 0, π}, {φ, 0, 2 π}, Mesh -> None, RegionFunction -> (#6 > 0.95 &), PlotStyle -> FaceForm[Orange, Yellow]]; Show[...


20

Update Compare two pictures. First is able to make mistake like you made the code. You need to do like this code using Mod[ArcTan[x, y], 2π]. h[r_,θ_] := 2 < r <= 5 && 3/4 π < θ < 3/2 π RegionPlot[ h[Sqrt[x^2 + y^2], Mod[ArcTan[x, y], 2π]], {x, -6, 6}, {y, -6, 6}] So I suggest to use ParametricPlot like this. rg = 6; mg = 3; ...


19

A simple alternative is to use Plot3D with both RegionFunction and Filling. Plot3D[y, {x, 0, 1}, {y, 0, 1}, RegionFunction -> Function[{x, y, z}, x^2 + y^2 <= 1 && x >= 0 && y >= 0 && z >= 0], Filling -> 0, FillingStyle -> Opacity[.75], PlotStyle -> Opacity[.5], AxesLabel -> (Style[#, 14, Bold] &...


19

Just wanted to add purely mathematical approach using complex mapping technique. PolyMap[n_, z_] := z Hypergeometric2F1[1/n, 2/n, (n + 1)/n, z^n] (* Integrate[1/(1 - ξ^n)^(2/n), {ξ, 0, z}] *) g = GraphicsGrid[ Table[ ParametricPlot[ z = PolyMap[n, r (Cos[t] + I Sin[t])]; {Re[z], Im[z]}, {t, 0, 2 π}, PlotRange -> All, Axes -> False] /. ...


19

Many solutions similar to how to get $n$ equidistributed points on the unit sphere are possible, especially if one can accept that points are not on the edges of a region. For instance, one can use analytical Lloyd's method: With[{reg = RegularPolygon[5]}, Nest[RegionNearest[reg][ RegionCentroid@RegionIntersection[reg, #] & /@ ...


18

Perhaps more a comment: note differences: r = RandomReal[{0.5, 1}, {10000, 2}]; Show[ListPlot[Sort@GatherBy[r, Times @@ # < 0.5 &], PlotStyle -> {{Red}, Blue}], Plot[1/(2 x), {x, 0.5, 1}, PlotStyle -> Green], Frame -> True] compared with: ListPlot[{#, RandomReal[{0.5, 1/(2 #)}]} & /@ RandomReal[{0.5, 1}, 10000], PlotStyle -> ...


17

In principal you should be able to do r = RegionDifference[Ball[{0, 0, 0}], Ball[{0, 0, 1}]]; rp = RegionPlot3D[r, PlotPoints -> 50]; DiscretizeGraphics[rp] Unfortunately, this does not work and is hopefully improved in a future version. One thing you can do, however, is use the finite element mesh generator for this: Needs["NDSolve`FEM`"] m = ...


17

Update Silvia proposed a much faster algorithm that I believe produces I uniform distribution. Here is my implementation of it. pointsInMask2[mask_Image, n_Integer, range : {_, _} : {0, 1/2}] := Reverse @ ImageData @ Binarize[mask, range]\[Transpose] // SparseArray[#]["NonzeroPositions"] & // RandomChoice[#, n] + RandomReal[{-1, 0}, {n, 2}] ...


17

Assuming you just ommitted the parentheses and meant $1/(2q) > p$, then this works q = RandomReal[{0.5, 1}] p = RandomReal[{0.5, 1/(2 q)}] Edit: The above code will generate 2 random numbers that satisfy the given criteria, they won't be sampling the same distribution. qlist = RandomReal[{0.5, 1.0}, 10000]; plist = RandomReal[{0.5, 1/(2 #)}] & /...


17

Since you mention that you want to use the rounded polygon in NDSolve[] as a region, you might want to look at the following construction: With[{r = 1/5 (* rounding radius *)}, rp = DiscretizeRegion[ ImplicitRegion[RegionDistance[ Polygon[CirclePoints[{1 - 2 Sqrt[5 - 2 Sqrt[5]] r, π/10}, 5]], {x, y}] <= r Sqrt[(5 - ...


17

Using RandomPoint[] with TubeMesh[] (routines from here and here) does the job: helix = First[Cases[Normal[ParametricPlot3D[{6 Cos[t], 6 Sin[t], t}, {t, -2 π, 4 π}, MaxRecursion -> 1, PlotPoints -> 75]], Line[l_] :> l, ∞]]; tube = TubeMesh[helix, 1/2, "CapForm" -> "Round"]; ...


17

In the documentation of Area: The area of a region of dimension three or higher is $\infty$: For the surface area you can do: Area @ RegionBoundary @ Ellipsoid[{0, 0, 0}, {1, 2, 3}] π (2 + 8 Sqrt[2] EllipticE[ArcCos[1/3], 27/32] + Sqrt[2] EllipticF[ArcCos[1/3], 27/32])


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