Float Quat::GetAngle() const { Float _w=w; if (_w<-1.f) _w=-1.f; else if (_w>1.f) _w=1.f; Float s=Sqrt(1.f-_w*_w); return s>Float_Eps ? ACos(_w)*2.f : 0.f; }
Quat MUST_USE_RESULT Quat::RotateFromTo(const float3 &sourceDirection, const float3 &targetDirection) { assume(sourceDirection.IsNormalized()); assume(targetDirection.IsNormalized()); // If sourceDirection == targetDirection, the cross product comes out zero, and normalization would fail. In that case, pick an arbitrary axis. float3 axis = sourceDirection.Cross(targetDirection); float oldLength = axis.Normalize(); if (oldLength != 0.f) { float halfCosAngle = 0.5f*sourceDirection.Dot(targetDirection); float cosHalfAngle = Sqrt(0.5f + halfCosAngle); float sinHalfAngle = Sqrt(0.5f - halfCosAngle); return Quat(axis.x * sinHalfAngle, axis.y * sinHalfAngle, axis.z * sinHalfAngle, cosHalfAngle); } else return Quat(1.f, 0.f, 0.f, 0.f); }
Real ErrorAccumulator::Value() const { if(IsInf(norm)) return accumulator; if(norm == 1.0) { if(mean) return accumulator/sumWeights; return accumulator; } if(norm == 2.0) { if(mean && !root) return accumulator/sumWeights; else if(mean && root) return Sqrt(accumulator/sumWeights); else if(root) return Sqrt(accumulator); return accumulator; } if(mean && !root) return accumulator/sumWeights; else if(mean && root) return Pow(accumulator/sumWeights,1.0/norm); else if(root) return Pow(accumulator,1.0/norm); return accumulator; }
/// See http://paulbourke.net/geometry/platonic/ Polyhedron Polyhedron::Icosahedron(const float3 ¢erPos, float scale, bool ccwIsFrontFacing) { float a = 0.5f; float phi = (1.f + Sqrt(5.f)) / 2.f; float b = 1.f / (2.f * phi); const float3 vertices[12] = { float3( 0, b, -a), float3( b, a, 0), float3(-b, a, 0), float3( 0, b, a), float3( 0, -b, a), float3(-a, 0, b), float3( a, 0, b), float3( 0, -b, -a), float3(-a, 0, -b), float3(-b, -a, 0), float3( b, -a, 0), float3( a, 0, -b) }; const int faces[20][3] = { { 0, 1, 2 }, { 3, 2, 1 }, { 3, 4, 5 }, { 3, 6, 4 }, { 0, 7, 11 }, { 0, 8, 7 }, { 4, 10, 9 }, { 7, 9, 10 }, { 2, 5, 8 }, { 9, 8, 5 }, { 1, 11, 6 }, { 10, 6, 11 }, { 3, 5, 2 }, { 3, 1, 6 }, { 0, 2, 8 }, { 0, 11, 1 }, { 7, 8, 9 }, { 7, 10, 11 }, { 4, 9, 5 }, { 4, 6, 10 } }; Polyhedron p; for(int i = 0; i < 12; ++i) p.v.push_back(vertices[i]*scale + centerPos); for(int i = 0; i < 20; ++i) { Face f; for(int j = 0; j < 3; ++j) f.v.push_back(faces[i][j]); p.f.push_back(f); } if (!ccwIsFrontFacing) p.FlipWindingOrder(); return p; }
TwoNormUpperBound( const DistMatrix<F>& A ) { #ifndef RELEASE CallStackEntry entry("TwoNormUpperBound"); #endif typedef BASE(F) R; const R m = A.Height(); const R n = A.Width(); const R maxNorm = MaxNorm( A ); const R oneNorm = OneNorm( A ); const R infNorm = InfinityNorm( A ); R upperBound = std::min( Sqrt(m*n)*maxNorm, Sqrt(m)*infNorm ); upperBound = std::min( upperBound, Sqrt(n)*oneNorm ); upperBound = std::min( upperBound, Sqrt( oneNorm*infNorm ) ); return upperBound; }
// DiffusionReflectance Public Methods DiffusionReflectance(const Spectrum &sigma_a, const Spectrum &sigmap_s, float eta) { A = (1.f + Fdr(eta)) / (1.f - Fdr(eta)); sigmap_t = sigma_a + sigmap_s; sigma_tr = Sqrt(3.f * sigma_a * sigmap_t); alphap = sigmap_s / sigmap_t; zpos = Spectrum(1.f) / sigmap_t; zneg = -zpos * (1.f + (4.f/3.f) * A); }
void genericE6SSM_susy_scale_constraint<Two_scale>::initialize() { const auto m0 = INPUTPARAMETER(m0); const auto m12 = INPUTPARAMETER(m12); initial_scale_guess = Sqrt(Sqr(m0) + 4*Sqr(m12)); scale = initial_scale_guess; }
float3 Circle::ClosestPointToDisc(const float3 &point) const { float3 pointOnPlane = ContainingPlane().Project(point); float3 diff = pointOnPlane - pos; float dist = diff.LengthSq(); if (dist > r*r) diff = diff * (r / Sqrt(dist)); return pos + diff; }
bool TriangIsNormal( const ElementalMatrix<F>& UPre, Base<F> tol ) { DistMatrixReadProxy<F,F,MC,MR> UProx( UPre ); auto& U = UProx.GetLocked(); const Base<F> diagFrob = FrobeniusNorm(GetDiagonal(U)); const Base<F> upperFrob = FrobeniusNorm( U ); const Base<F> offDiagFrob = Sqrt(upperFrob*upperFrob-diagFrob*diagFrob); return offDiagFrob <= tol*diagFrob; }
void genericE6SSM_initial_guesser<Two_scale>::guess_susy_parameters() { QedQcd leAtMt(oneset); const double MZ = Electroweak_constants::MZ; const double MW = Electroweak_constants::MW; const double sinThetaW2 = 1.0 - Sqr(MW / MZ); const double mtpole = leAtMt.displayPoleMt(); mu_guess = leAtMt.displayMass(mUp); mc_guess = leAtMt.displayMass(mCharm); mt_guess = leAtMt.displayMass(mTop) - 30.0; md_guess = leAtMt.displayMass(mDown); ms_guess = leAtMt.displayMass(mStrange); mb_guess = leAtMt.displayMass(mBottom); me_guess = leAtMt.displayMass(mElectron); mm_guess = leAtMt.displayMass(mMuon); mtau_guess = leAtMt.displayMass(mTau); // guess gauge couplings at mt const DoubleVector alpha_sm(leAtMt.getGaugeMu(mtpole, sinThetaW2)); model->set_g1(sqrt(4.0 * M_PI * alpha_sm(1))); model->set_g2(sqrt(4.0 * M_PI * alpha_sm(2))); model->set_g3(sqrt(4.0 * M_PI * alpha_sm(3))); model->set_scale(mtpole); // apply user-defined initial guess at the low scale const auto TanBeta = INPUTPARAMETER(TanBeta); const auto vSInput = INPUTPARAMETER(vSInput); MODEL->set_vd(SM(vev)/Sqrt(1 + Sqr(TanBeta))); MODEL->set_vu((TanBeta*SM(vev))/Sqrt(1 + Sqr(TanBeta))); MODEL->set_vs(vSInput); MODEL->set_mHd2(Sqr(SM(MZ))); MODEL->set_mHu2(Sqr(SM(MZ))); MODEL->set_ms2(Sqr(SM(MZ))); MODEL->set_BMuPr(Sqr(SM(MZ))); MODEL->set_MuPr(SM(MZ)); calculate_Yu_DRbar(); calculate_Yd_DRbar(); calculate_Ye_DRbar(); }
inline typename Base<F>::type internal::FrobeniusNorm( const DistMatrix<F,MC,MR>& A ) { #ifndef RELEASE PushCallStack("internal::FrobeniusNorm"); #endif typedef typename Base<F>::type R; R localScale = 0; R localScaledSquare = 1; for( int jLocal=0; jLocal<A.LocalWidth(); ++jLocal ) { for( int iLocal=0; iLocal<A.LocalHeight(); ++iLocal ) { const R alphaAbs = Abs(A.GetLocalEntry(iLocal,jLocal)); if( alphaAbs != 0 ) { if( alphaAbs <= localScale ) { const R relScale = alphaAbs/localScale; localScaledSquare += relScale*relScale; } else { const R relScale = localScale/alphaAbs; localScaledSquare = localScaledSquare*relScale*relScale + 1; localScale = alphaAbs; } } } } // Find the maximum relative scale R scale; mpi::AllReduce( &localScale, &scale, 1, mpi::MAX, A.Grid().VCComm() ); R norm = 0; if( scale != 0 ) { // Equilibrate our local scaled sum to the maximum scale R relScale = localScale/scale; localScaledSquare *= relScale*relScale; // The scaled square is now simply the sum of the local contributions R scaledSquare; mpi::AllReduce ( &localScaledSquare, &scaledSquare, 1, mpi::SUM, A.Grid().VCComm() ); norm = scale*Sqrt(scaledSquare); } #ifndef RELEASE PopCallStack(); #endif return norm; }
std::set<Argument> SolveQuadraticEquation( Argument const& origin, Value const& a0, Derivative<Value, Argument> const& a1, Derivative<Derivative<Value, Argument>, Argument> const& a2) { using Derivative1 = Derivative<Value, Argument>; using Discriminant = Square<Derivative1>; std::set<Argument> solutions; // This algorithm is after section 1.8 of Accuracy and Stability of Numerical // Algorithms, Second Edition, Higham, ISBN 0-89871-521-0. static Discriminant const discriminant_zero{}; // Use compensated summation for the discriminant because there can be // cancellations. DoublePrecision<Discriminant> discriminant(a1 * a1); discriminant.Increment(-4.0 * a0 * a2); if (discriminant.value == discriminant_zero && discriminant.error == discriminant_zero) { // One solution. solutions.insert(origin - 0.5 * a1 / a2); } else if (discriminant.value < discriminant_zero || (discriminant.value == discriminant_zero && discriminant.error < discriminant_zero)) { // No solution. } else { // Two solutions. Compute the numerator of the larger one. Derivative1 numerator; static Derivative1 derivative_zero{}; if (a1 > derivative_zero) { numerator = -a1 - Sqrt(discriminant.value + discriminant.error); } else { numerator = -a1 + Sqrt(discriminant.value + discriminant.error); } solutions.insert(origin + numerator / (2.0 * a2)); solutions.insert(origin + (2.0 * a0) / numerator); } return solutions; }
void FoxLi( Matrix<Complex<Real>>& A, Int n, Real omega ) { DEBUG_CSE typedef Complex<Real> C; const Real pi = 4*Atan( Real(1) ); const C phi = Sqrt( C(0,omega/pi) ); // Compute Gauss quadrature points and weights Matrix<Real> d, e; Zeros( d, n, 1 ); e.Resize( n-1, 1 ); for( Int j=0; j<n-1; ++j ) { const Real betaInv = 2*Sqrt(1-Pow(j+Real(1),-2)/4); e(j) = 1/betaInv; } Matrix<Real> x, Z; HermitianTridiagEig( d, e, x, Z, UNSORTED ); auto z = Z( IR(0), ALL ); Matrix<Real> sqrtWeights( z ), sqrtWeightsTrans; for( Int j=0; j<n; ++j ) sqrtWeights(0,j) = Sqrt(Real(2))*Abs(sqrtWeights(0,j)); herm_eig::Sort( x, sqrtWeights, ASCENDING ); Transpose( sqrtWeights, sqrtWeightsTrans ); // Form the integral operator A.Resize( n, n ); for( Int j=0; j<n; ++j ) { for( Int i=0; i<n; ++i ) { const Real theta = -omega*Pow(x(i)-x(j),2); const Real realPart = Cos(theta); const Real imagPart = Sin(theta); A(i,j) = phi*C(realPart,imagPart); } } // Apply the weighting DiagonalScale( LEFT, NORMAL, sqrtWeightsTrans, A ); DiagonalScale( RIGHT, NORMAL, sqrtWeightsTrans, A ); }
inline float RSqrt(float _x) { #if USE_CRT_MATH return 1 / Sqrt(_x); #else float _r; __asm rsqrtss xmm0, _x __asm movss _r, xmm0 return _r; #endif }
// Return distance from one point to another - non-member version TFloat32 Distance ( const CVector3& p1, const CVector3& p2 ) { TFloat32 distX = p1.x - p2.x; TFloat32 distY = p1.y - p2.y; TFloat32 distZ = p1.z - p2.z; return Sqrt( distX*distX + distY*distY + distZ*distZ ); }
void Target_Octahedron::GenerateVertices(void) { const real sqrt2 = (real)1. / Sqrt((real)2.); const real al = sqrt2 * shpar[0]; vertices[0].Set(zero_, zero_, al); vertices[1].Set( al, zero_, zero_); vertices[2].Set(zero_, al, zero_); vertices[3].Set( -al, zero_, zero_); vertices[4].Set(zero_, -al, zero_); vertices[5].Set(zero_, zero_, -al); }
Rovnice() : d1( Sqrt((x+Mi)*(x+Mi) + y*y) ), d2( Sqrt((x-MiC)*(x-MiC) +y*y) ), x1 ( x + 2*y1 - MiC / (d1*d1*d1) * (x+Mi) - Mi / (d2*d2*d2) * (x-MiC), 0 // poŸ. podm¡nka ), y1( y -2*x1 -MiC*y / (d1*d1*d1) -Mi*y / (d2*d2*d2), // -2.00158510637908255224053786224 // poŸ. podm¡nka -2.0317326295573368357302057924 // poŸ. podm¡nka ), x(x1,0.994), y(y1) {}
bool Eigenvalues(const Matrix2& A,Real& lambda1,Real& lambda2) { Real trace=A.trace(); Real det=A.determinant(); Real temp2 = Sqr(trace) - 4.0*det; if(temp2 < 0) return false; Real temp=Sqrt(temp2); lambda1 = 0.5*(trace + temp); lambda2 = 0.5*(trace - temp); return true; }
inline bool TriangIsNormal( const ElementalMatrix<F>& UPre, Base<F> tol ) { auto UPtr = ReadProxy<F,MC,MR>( &UPre ); auto& U = *UPtr; const Base<F> diagFrob = FrobeniusNorm(GetDiagonal(U)); const Base<F> upperFrob = FrobeniusNorm( U ); const Base<F> offDiagFrob = Sqrt(upperFrob*upperFrob-diagFrob*diagFrob); return offDiagFrob <= tol*diagFrob; }
double caplet_lmm(const Date& todaysDate_, const Date& settlementDate_, const Date& maturity_, Rate spot_, Rate strike, Rate Numeraire, //zero-coupon bond //Volatility volatility double correl, double a, double b, double c, double d ) { //SavedSettings backup; const Size size = 10; #if defined(QL_USE_INDEXED_COUPON) const Real tolerance = 1e-5; #else const Real tolerance = 1e-12; #endif boost::shared_ptr<IborIndex> index = makeIndex(); boost::shared_ptr<LiborForwardModelProcess> process(new LiborForwardModelProcess(size, index)); // set-up pricing engine const boost::shared_ptr<OptionletVolatilityStructure> capVolCurve = makeCapVolCurve(Settings::instance().evaluationDate()); Array variances = LfmHullWhiteParameterization(process, capVolCurve).covariance(0.0).diagonal(); boost::shared_ptr<LmVolatilityModel> volaModel(new LmFixedVolatilityModel(Sqrt(variances),process->fixingTimes())); boost::shared_ptr<LmCorrelationModel> corrModel(new LmExponentialCorrelationModel(size, correl)); boost::shared_ptr<AffineModel> model(new LiborForwardModel(process, volaModel, corrModel)); const Handle<YieldTermStructure> termStructure = process->index()->forwardingTermStructure(); boost::shared_ptr<AnalyticCapFloorEngine> engine1(new AnalyticCapFloorEngine(model, termStructure)); boost::shared_ptr<Cap> cap1(new Cap(process->cashFlows(),std::vector<Rate>(size, strike))); cap1->setPricingEngine(engine1); return cap1->NPV(); }
Base<Field> FrobeniusNorm( const SparseMatrix<Field>& A ) { EL_DEBUG_CSE typedef Base<Field> Real; Real scale = 0; Real scaledSquare = 1; const Int numEntries = A.NumEntries(); const Field* valBuf = A.LockedValueBuffer(); for( Int k=0; k<numEntries; ++k ) UpdateScaledSquare( valBuf[k], scale, scaledSquare ); return scale*Sqrt(scaledSquare); }
void Fourier( Matrix<Complex<Real>>& A, Int n ) { EL_DEBUG_CSE A.Resize( n, n ); const Real pi = 4*Atan( Real(1) ); const Real nSqrt = Sqrt( Real(n) ); auto fourierFill = [=]( Int i, Int j ) -> Complex<Real> { const Real theta = -2*pi*i*j/n; return Complex<Real>(Cos(theta),Sin(theta))/nSqrt; }; IndexDependentFill( A, function<Complex<Real>(Int,Int)>(fourierFill) ); }
void CMSSM_susy_scale_constraint<Two_scale>::initialize() { assert(model && "CMSSM_susy_scale_constraint<Two_scale>::" "initialize(): model pointer is zero."); const auto m0 = INPUTPARAMETER(m0); const auto m12 = INPUTPARAMETER(m12); initial_scale_guess = Sqrt(Sqr(m0) + 4*Sqr(m12)); scale = initial_scale_guess; }
pair<ULL, ULL> Pell(int n) { static ULL p[50] = {0, 1}, q[50] = {1, 0}, g[50] = {0, 0}, h[50] = {0, 1}, a[50]; ULL t = a[2] = Sqrt(n); for (int i = 2; ; ++i) { g[i] = -g[i - 1] + a[i] * h[i - 1]; h[i] = (n - g[i] * g[i]) / h[i - 1]; a[i + 1] = (g[i] + t) / h[i]; p[i] = a[i] * p[i - 1] + p[i - 2]; q[i] = a[i] * q[i - 1] + q[i - 2]; if (p[i] * p[i] - n * q[i] * q[i] == 1) return make_pair(p[i], q[i]); } return make_pair(-1, -1); }
void Sphere::Enclose(const float3 &point) { float3 d = point - pos; float dist2 = d.LengthSq(); if (dist2 > r*r) { float dist = Sqrt(dist2); float newRadius = (r + dist) / 2.f; pos += d * (newRadius - r) / dist; r = newRadius; } }
void Fourier( AbstractBlockDistMatrix<Complex<Real>>& A, Int n ) { DEBUG_ONLY(CallStackEntry cse("Fourier")) A.Resize( n, n ); const Real pi = 4*Atan( Real(1) ); const Real nSqrt = Sqrt( Real(n) ); auto fourierFill = [=]( Int i, Int j ) -> Complex<Real> { const Real theta = -2*pi*i*j/n; return Complex<Real>(Cos(theta),Sin(theta))/nSqrt; }; IndexDependentFill( A, function<Complex<Real>(Int,Int)>(fourierFill) ); }
static void FindVertexAngles(PatchMesh &pm, float *vang) { int i; for (i=0; i<pm.numVerts + pm.numVecs; i++) vang[i] = 0.0f; for (i=0; i<pm.numPatches; i++) { Patch &p = pm.patches[i]; for (int j=0; j<p.type; j++) { Point3 d1 = pm.vecs[p.vec[j*2]].p - pm.verts[p.v[j]].p; Point3 d2 = pm.vecs[p.vec[((j+p.type-1)%p.type)*2+1]].p - pm.verts[p.v[j]].p; float len = LengthSquared(d1); if (len == 0) continue; d1 /= Sqrt(len); len = LengthSquared (d2); if (len==0) continue; d2 /= Sqrt(len); float cs = DotProd (d1, d2); if (cs>=1) continue; // angle of 0 if (cs<=-1) vang[p.v[j]] += PI; else vang[p.v[j]] += (float) acos (cs); } } }
void StackedGeometricColumnScaling ( const DistMatrix<Field, U,V >& A, const DistMatrix<Field, U,V >& B, DistMatrix<Base<Field>,V,STAR>& geomScaling ) { EL_DEBUG_CSE // NOTE: Assuming A.ColComm() == B.ColComm() and that the row alignments // are equal typedef Base<Field> Real; DistMatrix<Real,V,STAR> maxScalingA(A.Grid()), maxScalingB(A.Grid()); ColumnMaxNorms( A, maxScalingA ); ColumnMaxNorms( B, maxScalingB ); const Int mLocalA = A.LocalHeight(); const Int mLocalB = B.LocalHeight(); const Int nLocal = A.LocalWidth(); geomScaling.AlignWith( maxScalingA ); geomScaling.Resize( A.Width(), 1 ); auto& ALoc = A.LockedMatrix(); auto& BLoc = B.LockedMatrix(); auto& geomScalingLoc = geomScaling.Matrix(); auto& maxScalingALoc = maxScalingA.Matrix(); auto& maxScalingBLoc = maxScalingB.Matrix(); for( Int jLoc=0; jLoc<nLocal; ++jLoc ) { Real minAbs = Max(maxScalingALoc(jLoc),maxScalingBLoc(jLoc)); for( Int iLoc=0; iLoc<mLocalA; ++iLoc ) { const Real absVal = Abs(ALoc(iLoc,jLoc)); if( absVal > 0 && absVal < minAbs ) minAbs = Min(minAbs,absVal); } for( Int iLoc=0; iLoc<mLocalB; ++iLoc ) { const Real absVal = Abs(BLoc(iLoc,jLoc)); if( absVal > 0 && absVal < minAbs ) minAbs = Min(minAbs,absVal); } geomScalingLoc(jLoc) = minAbs; } mpi::AllReduce( geomScaling.Buffer(), nLocal, mpi::MIN, A.ColComm() ); for( Int jLoc=0; jLoc<nLocal; ++jLoc ) { const Real maxAbsA = maxScalingALoc(jLoc); const Real maxAbsB = maxScalingBLoc(jLoc); const Real maxAbs = Max(maxAbsA,maxAbsB); const Real minAbs = geomScalingLoc(jLoc); geomScalingLoc(jLoc) = Sqrt(minAbs*maxAbs); } }
void Tartet::Sizer(void) { dx = manager->CashedDx(); // // Current version of TARTET is restricted to cubic lattices real s = shpar[0]; // // Set XOFF (and IMIN,IMAX): minJx = -(int)(s * Sqrt(onex_ / (real)24.)); xoff = half_ - s * Sqrt(onex_ / (real)24.) - minJx; maxJx = minJx + (int)(s * Sqrt(twox_ / (real)3.) + half_) - 1; // // Set YOFF (and JMIN,JMAX): minJy = -(int)(s / Sqrt(12.)); yoff = half_ - s / Sqrt(12.) - minJy; maxJy = minJy + (int)(s * Sqrt(0.75) + half_) - 1; // // Set ZOFF (and KMIN,KMAX): Determine whether S is closest to even or odd int. (Temporarily let KMIN be int which S is closest to) minJz = (int)(s + half_); // // If KMIN is even, then ZOFF=0.5 // If KMIN is odd, then ZOFF=0. zoff = zero_; if (minJz % 2 == 0) zoff = half_; minJz = -(int)(half_ * s + zoff); maxJz = minJz + (int)(s + half_) - 1; AllocateArrays(maxJx - minJx + 1, maxJy - minJy + 1, maxJz - minJz + 1); }
void UniformHelmholtzGreens( Matrix<Complex<Real>>& A, Int n, Real lambda ) { EL_DEBUG_CSE typedef Complex<Real> C; const Real pi = 4*Atan( Real(1) ); const Real k0 = 2*pi/lambda; // Generate a list of n uniform samples from the 3D unit ball Matrix<Real> X(3,n); for( Int j=0; j<n; ++j ) { Real x0, x1, x2; // Sample uniformly from [-1,+1]^3 until a point is drawn from the ball while( true ) { x0 = SampleUniform( Real(-1), Real(1) ); x1 = SampleUniform( Real(-1), Real(1) ); x2 = SampleUniform( Real(-1), Real(1) ); const Real radiusSq = x0*x0 + x1*x1 + x2*x2; if( radiusSq > 0 && radiusSq <= 1 ) break; } X(0,j) = x0; X(1,j) = x1; X(2,j) = x2; } A.Resize( n, n ); for( Int j=0; j<n; ++j ) { const Real xj0 = X(0,j); const Real xj1 = X(1,j); const Real xj2 = X(2,j); for( Int i=0; i<n; ++i ) { if( i == j ) { A(i,j) = 0; } else { const Real d0 = X(0,i)-xj0; const Real d1 = X(1,i)-xj1; const Real d2 = X(2,i)-xj2; const Real gamma = k0*Sqrt(d0*d0+d1*d1+d2*d2); const Real realPart = Cos(gamma)/gamma; const Real imagPart = Sin(gamma)/gamma; A(i,j) = C(realPart,imagPart); } } } }