Hot answers tagged

53

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 ...


33

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 ...


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

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

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} = ...


26

It would be nice if UniformDistribution worked on arbitrary regions, then we could simply do RandomVariate[UniformDistribution[region]]. Someone at Wolfram should get on that. In the meantime, it seems we have to write our own sampling routines. @m_goldberg's answer is very nice (vote it up!) and uses rejection sampling, which works for arbitrary regions. ...


23

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: Using MeshFunctions and Mesh in RegionPlot: RegionPlot[Evaluate[Region`RegionProperty[Rationalize /@ blob, {x, y}, "FastDescription"][[1, 2]]], {x, -3, 3}, {y, -3, 3}, Mesh -> 50, MeshFunctions -> {#1 + #2 &, #1 - #2 &}, MeshStyle -> White, PlotStyle -> Directive[{Thick, Blue}]] With settings MeshStyle -> GrayLevel[....


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 ...


22

Just increase the number of PlotPoints RegionPlot[x^2 < y && y < x^4, {x, -3, 3}, {y, 0, 3}, PlotPoints -> 100]


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

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 ...


21

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

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

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[...


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] &...


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 -> ...


18

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] /. ...


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

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

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, #] & /@ ...


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])


16

While not positive, I believe the answer is that RegionPlot does not support spherical (or other non-Cartesian) coordinates natively. If correct, I guess the question becomes "What's the easiest way to plot a region defined in terms of spherical coordinates, without resorting to converting the equations by hand?" V9 has commands to ease this process. ...


16

Or, the MaxRecursion: RegionPlot[x^2 < y && y < x^4, {x, -3, 3}, {y, 0, 3}, MaxRecursion -> 8] The plot commands generally use a adaptive procedure that is applied recursively. MaxRecursion controls how many times this recursion can be applied. PlotPoints by contrast, simply indicates how many points should be used in the initial grid. ...


16

Βαγγέλη, you can use an appropriate RegionFunction: V = 1/2*(x^2 + y^2 + z^2) + (x^2*y^2 + x^2*z^2 + y^2*z^2 - x^2*y^2*z^2); E0 = 7; S0 = ContourPlot3D[V == E0, {x, -4, 4}, {y, -4, 4}, {z, -4, 4}, PlotPoints -> 70, PerformanceGoal -> "Speed", Mesh -> None, ContourStyle -> Directive[Green, Opacity[0.3], Specularity[White, 30]], ...


16

The inertia tensor is defined as an integral of the following tensor over the body region vars = {x, y, z}; r2 = IdentityMatrix[3] Tr[#] - # &@Outer[Times, vars, vars]; r2 // MatrixForm It is very simple to do with integration over a region Integrate[r2, vars ∈ region] It can be wrapped in the following function inertiaTensor[reg_, assum_: {}] := ...


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