How to use QR decomposition of Extreme optimization - f#

http://social.msdn.microsoft.com/Forums/vstudio/en-US/7e952c45-2494-4650-aa61-89d5ea21f1f3/how-to-use-qr-decomposition-of-extreme-optimization
How to use QR decomposition of Extreme optimization
No parameterless constructor defined for this object.
let TwelvePalace : float[,] = Array2D.zeroCreate 4 3
TwelvePalace.[0,0] <- 1.0;
TwelvePalace.[0,1] <- 2.0;
TwelvePalace.[0,2] <- 3.0;
TwelvePalace.[1,0] <- 4.0;
TwelvePalace.[1,1] <- 5.0;
TwelvePalace.[1,2] <- 6.0;
TwelvePalace.[2,0] <- 7.0;
TwelvePalace.[2,1] <- 8.0;
TwelvePalace.[2,2] <- 9.0;
TwelvePalace.[3,0] <- 10.0;
TwelvePalace.[3,1] <- 11.0;
TwelvePalace.[3,2] <- 12.0;
let mutable iii = DenseMatrix.Create(TwelvePalace)
let QRProvider : QRDecomposition = iii.GetQRDecomposition()
let Q : DenseMatrix = QRProvider.OrthogonalFactor.ToDenseMatrix() // error here
let R : DenseMatrix = QRProvider.UpperTriangularFactor.ToDenseMatrix()

Related

Why I cant solve this puzzle?

Im tring to solve this puzzle by using dart lang but I didint solve it and I got large number + error! There is an puzzle image to understand it from here
can you help or give me a tip to solve this puzzle ~!
See full code :
import 'dart:math';
void main() {
var value;
int loob = 0;
do {
var z = new Random().nextInt(20);
var x = new Random().nextInt(20);
var y = new Random().nextInt(20);
var n = new Random().nextInt(20);
if (z - x == 9) {
print('DONE LOOB1 Z = $z and X = $x');
do {
var x = new Random().nextInt(20);
var n = new Random().nextInt(20);
if (x + n == 2) {
print('DONE LOOB2 X = $x and n = $n ');
do {
var n = new Random().nextInt(20);
var y = new Random().nextInt(20);
if (y - n == 14) {
print('DONE LOOB3 y = $y and n = $n ');
do {
var z = new Random().nextInt(20);
var y = new Random().nextInt(20);
if (z - y == 12) {
print('DONE LOOB4 z = $z and y = $y ');
value = 1;
} else {}
} while (value != 1);
} else {}
} while (value != 1);
value = 1;
} else {}
} while (value != 1);
value = 1;
} else {
null;
}
print(++loob);
} while (value != 1);
}
reslate code :
DONE LOOB1 Z = 11 and X = 2
DONE LOOB2 X = 2 and n = 0
DONE LOOB3 y = 14 and n = 0
DONE LOOB4 z = 17 and y = 5
Finshed
this is your algorithm issue, you are adding 0.1 to your variable every step, and it means all numbers are equal in the end you must create two mathematical equations and two unknown values and then solve them. this is the main approach to solve such problems.
Assume this picture like these Equations:
x - y = 9
x + n = 2
y - n = 14
z - y = 12
now you have 4 equations and 4 unknown.
you can solve this equation by this (Matrix manipulation) or this (substitution one unknown with another) on method.

Draw a sphere using sectors and stack WebGL

I'm trying to draw a sphere using sectors and stacks algorithm but it output nothing and do not know where is the problem. Any help?
I implemented the algorithm literally as written in: http://www.songho.ca/opengl/gl_sphere.html
Everything is working fine except the coloredShpere function
this is a photo of what appears to me when I run this function:
and you can find the whole code in: https://drive.google.com/open?id=1dnnkk1w7oq4O7hPTMeGRkyELwi4tcl5X
let mesh = createMesh(gl);
const PI = 3.1415926;
const r = 1.0;
const stackCount = 16;
const sectorCount = 16;
let x : number;
let y : number;
let z : number;
let xy : number;
let vertices: number[] = new Array();
let normals : number[] = new Array();
let texCoords : number[] = new Array();
let nx: number;
let ny: number;
let nz: number;
let lengthInv: number;
lengthInv = 1.0 / r;
let s: number;
let t: number;
let sectorStep = 2 * PI / sectorCount;
let stackStep = PI / stackCount;
let sectorAngle : number;
let stackAngle : number;
for(let i = 0; i<=stackCount; i++) {
stackAngle = PI/2 - i*stackStep; //-90 to +90
xy = r*Math.cos(stackAngle);
z = r*Math.sin(stackAngle);
for(let j = 0; j<=sectorCount; j++) {
sectorAngle = j*sectorAngle; //0 to 360
x = xy*Math.cos(sectorAngle);
y = xy*Math.sin(sectorAngle);
vertices.push(x);
vertices.push(y);
vertices.push(z);
nx = x * lengthInv;
ny = y * lengthInv;
nz = z * lengthInv;
normals.push(nx);
normals.push(ny);
normals.push(nz);
// vertex tex coord (s, t) range between [0, 1]
s = j / sectorCount;
t = i / stackCount;
texCoords.push(s);
texCoords.push(t);
}
}
// generate CCW index list of sphere triangles
// indices
// k1--k1+1
// | / |
// | / |
// k2--k2+1
let indices: number[] = new Array();
let k1 : number;
let k2 : number;
for(let i = 0; i<stackCount; i++) {
k1 = i * (sectorCount + 1); //frist stack
k2 = k1 + sectorCount + 1; //second stack
for(let j = 0; j<sectorCount; j++) {
//k1, k2, k1+1
if(i != 0) {
indices.push(k1);
indices.push(k2);
indices.push(k1+1);
}
//k1+1, k2, k2+1
if(i != (stackCount-1)) {
indices.push(k1+1);
indices.push(k2);
indices.push(k2+1);
}
}
}
mesh.setBufferData("positions", new Float32Array(vertices), gl.STATIC_DRAW);
//mesh.setBufferData("colors", new Uint8Array(), gl.STATIC_DRAW);
mesh.setElementsData(new Uint32Array(indices), gl.STATIC_DRAW);
//mesh.setBufferData("colors", new Uint8Array(), gl.STATIC_DRAW);
return mesh;
Suggestion: Learn how to use console.log and your browser's debugger
I didn't check if your code actually works or not but I did add these lines at the bottom of what you posted above
console.log(vertices);
console.log(indices);
and what I saw was
All those NaN values are clearly wrong
Stepping through the code comes to this line
sectorAngle = j*sectorAngle; //0 to 360
which is where the NaN is generated
which doesn't match the article you linked to
sectorAngle = j * sectorStep; // starting from 0 to 2pi
Whether or not that's the only issue I don't know but if there are more then use console.log and the debugger to help find the issue. One way to make the code easier to debug is set stackCount and sectorCount to something small like 4 and 2 respectively and then you should have some idea what all the values should be and you can compare with what values you are getting.
If someone interested to know the solution, this is the code after some improvements:
`
let mesh = createMesh(gl);
const PI = 3.1415926;
const r = 1.0;
let vertices = [];
let colors = [];
for(let i = 0; i<=verticalResolution; ++i) {
let theta = i * Math.PI / verticalResolution; //-90 to 90
let sinTheta = Math.sin(theta);
let cosTheta = Math.cos(theta);
for(let j = 0; j<=horizontalResolution; ++j) {
let phi = j * 2 * Math.PI / horizontalResolution; //0 to 360
let sinPhi = Math.sin(phi);
let cosPhi = Math.cos(phi);
let x = sinTheta*cosPhi;
let y = cosTheta;
let z = sinTheta*sinPhi;
vertices.push(r*x);
vertices.push(r*y);
vertices.push(r*z);
colors.push((x+1)/2*255);
colors.push((y+1)/2*255);
colors.push((z+1)/2*255);
colors.push(255);
}
}
// generate CCW index list of sphere triangles
// indices
// k1--k1+1
// | / |
// | / |
// k2--k2+1
let indices = [];
for(let i = 0; i<verticalResolution; ++i) {
for(let j = 0; j<horizontalResolution; ++j) {
let first = (i * (horizontalResolution + 1)) + j;
let second = first + horizontalResolution + 1;
indices.push(first);
indices.push(second);
indices.push(first+1);
indices.push(second);
indices.push(second+1);
indices.push(first+1);
}
}
mesh.setBufferData("positions", new Float32Array(vertices), gl.STATIC_DRAW);
mesh.setBufferData("colors", new Uint8Array(colors), gl.STATIC_DRAW);
mesh.setElementsData(new Uint32Array(indices), gl.STATIC_DRAW);
return mesh;`
Output of the code

comparing with equal operator in fsharp

If I have the next type:
type Color(r: float, g: float, b:float) =
member this.r = r
member this.g = g
member this.b = b
static member ( * ) (c1:Color, c2:Color) =
Color (c1.r*c2.r, c1.g*c2.g, c1.b*c2.b)
static member Zero = Color(0.0,0.0,0.0)
and I do:
let ca = Color(1.,1.,1.)
let cb = Color(1.,1.,1.)
ca = cb
I should obtain true, but the F# interactive via a script is giving me false
Instead, If I define as:
let ca = Color(1.,1.,1.)
let cb = ca
ca = cb
It returns true
Am I doing something wrong trying to compare two values of a defined type in this way?
How can I do it to obtain true as a result?
Thanks
The OP definition of Color is a class. Classes have referential equality by default, just like in C#. That means they're only equal if they literally are the same object (points to the same memory address).
Only the functional data types in F# have structural equality. These include records, discriminated unions, lists, and a few other types.
It'd be more idiomatic to define Color as a record:
type Color = { Red : float; Green : float; Blue : float }
This type has structural equality built in:
> let ca = { Red = 1.; Green = 1.; Blue = 1. };;
val ca : Color = {Red = 1.0;
Green = 1.0;
Blue = 1.0;}
> let cb = { Red = 1.; Green = 1.; Blue = 1. };;
val cb : Color = {Red = 1.0;
Green = 1.0;
Blue = 1.0;}
> ca = cb;;
val it : bool = true
If you want to define multiplication and zero for the type, you can do that as well:
let (*) x y = {
Red = x.Red * y.Red
Green = x.Green * y.Green
Blue = x.Blue * y.Blue }
let zero = { Red = 0.0; Green = 0.0; Blue = 0.0 }
This enables you to write, e.g.:
> let product = ca * cb;;
val product : Color = {Red = 1.0;
Green = 1.0;
Blue = 1.0;}
F# implements automatic memberwise comparison for records and unions, but not for classes. If you want to have it and construct values with the Color(r, g, b) syntax, you can use a single-case union. You will get pattern matching as a bonus (see my implementation of (*)).
type Color =
| Color of r: float * g: float * b: float
member this.r = let (Color(r, _, _)) = this in r
member this.g = let (Color(_, g, _)) = this in g
member this.b = let (Color(_, _, b)) = this in b
static member (*) (Color(r1, g1, b1), Color(r2, g2, b2)) =
Color(r1 * r2, g1 * g2, b1 * b2)
static member Zero = Color(0., 0., 0.)
To start you should read this page:
http://blogs.msdn.com/b/dsyme/archive/2009/11/08/equality-and-comparison-constraints-in-f-1-9-7.aspx
It does a great job of illustrating how equality works in F#.
As to your specific issue, you are looking at the difference between Reference Equality and Structural Equality. You can add the following annotation
[<CustomEquality; CustomComparison>]
And you can add overloads to the Equals method override x.Equals(other) to do your memberwise comparision

Convert C code into F#

I am looking to convert the following C code into F# (this is the fast inverse square root algorithm):
float Q_rsqrt( float number )
{
long i;
float x2, y;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // Extract bit pattern
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i; // Convert back to float.
y = y * ( 1.5F - ( x2 * y * y ) );
return y;
}
First of all you should do some research. Then if you stuck specify with what you have problem.
Here is solution by Kit Eason.
let fastInvSqrt (n : float32) : float32 =
let MAGIC_NUMBER : int32 = 0x5f3759df
let THREE_HALVES = 1.5f
let x2 = n * 0.5f
let i = MAGIC_NUMBER - (System.BitConverter.ToInt32(System.BitConverter.GetBytes(n), 0) >>> 1)
let y = System.BitConverter.ToSingle(System.BitConverter.GetBytes(i), 0)
y * (THREE_HALVES - (x2 * y * y))
// Examples:
let x = fastInvSqrt 4.0f
// Output: val x : float32 = 0.499153584f
let x' = 1. / sqrt(4.0)
// Output: val x' : float = 0.5
When it comes to performance and low-level optimization it is often a good idea to measure before and after. The fast-inverse trick is very cool but it's approximates the inverse square and the question is if tricky code like this is truely necessary these days (in the DOOM days when float performace was crap the trick was amazing).
Anyway so I built a simple performance test bench in order to compare the trivial implementation with the solution provided by Kit Eason/lad2025 and another one that doesn't allocate byte arrays.
open System
open System.Diagnostics
open System.Runtime.InteropServices
[<Literal>]
let MAGIC_NUMBER : int32 = 0x5f3759df
[<Literal>]
let THREE_HALVES = 1.5F
[<Literal>]
let HALF = 0.5F
[<Literal>]
let OUTER = 1000
[<Literal>]
let INNER = 10000
let inline invSqr (x : float32) : float32 = 1.F / sqrt x
let fInvSqr (x : float32) : float32 =
let x2 = x * 0.5f
// Allocates two byte arrays creating GC pressure ==> hurts performance
let i = MAGIC_NUMBER - (BitConverter.ToInt32(BitConverter.GetBytes(x), 0) >>> 1)
let y = BitConverter.ToSingle(BitConverter.GetBytes(i), 0)
y * (THREE_HALVES - (x2 * y * y))
// Susceptible to race conditions & endianess issues
[<StructLayout (LayoutKind.Explicit)>]
type Bits =
struct
[<FieldOffset(0)>]
val mutable f: float32
[<FieldOffset(0)>]
val mutable i: int32
end
let mutable bits = Bits ()
let fInvSqr2 (x : float32) : float32 =
let x2 = x * 0.5F
bits.f <- x
let i = MAGIC_NUMBER - (bits.i >>> 1)
bits.i <- i
let y = bits.f
y * (THREE_HALVES - (x2 * y * y))
let timeIt n (a : unit -> 'T) : int64 * 'T =
let r = a ()
let sw = Stopwatch ()
sw.Start ()
for i = 1 to n do
ignore <| a ()
sw.Stop ()
sw.ElapsedMilliseconds, r
[<EntryPoint>]
let main argv =
let testCases =
[|
"invSqr" , fun () ->
let mutable sum = 0.F
for x = 1 to INNER do
sum <- sum + invSqr (float32 x)
sum
"fInvSqr" , fun () ->
let mutable sum = 0.F
for x = 1 to INNER do
sum <- sum + fInvSqr (float32 x)
sum
"fInvSqr2" , fun () ->
let mutable sum = 0.F
for x = 1 to INNER do
sum <- sum + fInvSqr2 (float32 x)
sum
|]
for name, action in testCases do
printfn "Running %s %d times..." name (OUTER*INNER)
let elapsed, result = timeIt OUTER action
printfn "... it took %d ms product result: %f" elapsed result
0
The performance test result on my machine:
Running invSqr 10000000 times...
... it took 78 ms product result: 198.544600
Running fInvSqr 10000000 times...
... it took 311 ms product result: 198.358200
Running fInvSqr2 10000000 times...
... it took 49 ms product result: 198.358200
Press any key to continue . . .
So we see that fInvSqr is actually 3 times slower than the trivial solution, most likely because of the byte allocation. In addition the cost of GC is hidden in these numbers and might add non-deterministic performance degration.
fInvSqr2 seems to perform slightly better but there are drawbacks here as well
The result is off by 0.1%
The Bits trick is susceptible to race conditions (fixable)
The Bits trick is suspectible to endian issues (if you are run the program on a CPU with different endianess it might break)
Is the performance gains worth the drawbacks? Since a program probably is not just built up from inverse square operations the effective performance gain might be much smaller in reality. I have a hard time imagining a scenario where I would so presurres for performance I opt for the fast inverse trick today but then it all depends on your context.

Farseer, MonoGame, ball does not bounce

I have successfully integrated Farseer for XNA into MonoGame with little to no trouble. Stacking, complex dynamics, etc. all seem to be working fine, but I absolutely cannot make a ball bounce on a floor. When the ball touches the ground, it simply stops there and only moves away if pushed by another ball.
My code (in F#, but it should be clear enough; <- means assignment, everything else is the same as C#) for creating the ball and the ground is:
member physics.CreateBall(x:float32<m>,y:float32<m>,r:float32<m>,m:float32<kg>,dynamic:bool) =
let myBody = Factories.BodyFactory.CreateBody(physics.Physics, Microsoft.Xna.Framework.Vector2(x * 1.0f<1/m> + random_range -30.0f 30.0f, y * 1.0f<1/m>) * PhysicsWorld.Scale)
do myBody.LastFrameUpdate <- Casanova.Core.get_frame_counter()
do myBody.BodyType <- if dynamic then BodyType.Dynamic else BodyType.Static
do myBody.Restitution <- 1.0f
do myBody.Friction <- 0.0f
do myBody.Mass <- m * 1.0f<_>
let circleShape = new CircleShape(r * PhysicsWorld.Scale * 1.0f<1/m>, 1.0f)
let fixture = myBody.CreateFixture(circleShape)
{ Body = myBody; Tick = Rule.Create 0 }
member physics.CreateBox(x:float32<m>,y:float32<m>,w:float32<m>,h:float32<m>,m:float32<kg>,dynamic:bool) =
let myBody = Factories.BodyFactory.CreateBody(physics.Physics, Microsoft.Xna.Framework.Vector2(x * 1.0f<1/m>, y * 1.0f<1/m>) * PhysicsWorld.Scale)
do myBody.LastFrameUpdate <- Casanova.Core.get_frame_counter()
do myBody.BodyType <- if dynamic then BodyType.Dynamic else BodyType.Static
do myBody.Restitution <- 1.0f
do myBody.Friction <- 0.0f
do myBody.Mass <- m * 1.0f<_>
let rectangle = PolygonTools.CreateRectangle(w * PhysicsWorld.Scale * 1.0f<1/m>, h * PhysicsWorld.Scale * 1.0f<1/m>)
let boxShape = PolygonShape(rectangle, 1.0f)
let fixture = myBody.CreateFixture(boxShape)
{ Body = myBody; Tick = Rule.Create 0 }
The simplest solution of all. The code above was almost correct, minus the initialization order. Here is the working version for future reference:
let myBody = Factories.BodyFactory.CreateBody(physics.Physics, Microsoft.Xna.Framework.Vector2(x * 1.0f<1/m>, y * 1.0f<1/m>) * PhysicsWorld.Scale)
let rectangle = PolygonTools.CreateRectangle(w * PhysicsWorld.Scale * 1.0f<1/m>, h * PhysicsWorld.Scale * 1.0f<1/m>)
let boxShape = PolygonShape(rectangle, 1.0f)
let fixture = myBody.CreateFixture(boxShape)
do myBody.LastFrameUpdate <- Casanova.Core.get_frame_counter()
do myBody.BodyType <- if dynamic then BodyType.Dynamic else BodyType.Static
do myBody.Restitution <- restitution
do myBody.Friction <- friction
do myBody.Mass <- m * 1.0f<_>

Resources