void Color::LinearInterp(const Color& dest,float s) { a = LinearInterpolation(a,dest.a,s); r = LinearInterpolation(r,dest.r,s); g = LinearInterpolation(g,dest.g,s); b = LinearInterpolation(b,dest.b,s); }
//----------------------------------------------------------------------------- //! コンストラクタ(カラー) //----------------------------------------------------------------------------- Vector4::Vector4(const Color color) { // 0.0f~1.0fにコンバート _x = LinearInterpolation(0.0f, 1.0f, color._r, 255); _y = LinearInterpolation(0.0f, 1.0f, color._g, 255); _z = LinearInterpolation(0.0f, 1.0f, color._b, 255); _w = LinearInterpolation(0.0f, 1.0f, color._a, 255); }
double BlackScholes(double inSpot, double inStrike, double inSigma, double inMaturity, string inCallPut, vector<double>& inIRRate, vector<double>& inIRTime){ double lReturn; double d1; double d2; double lSpotRate; double lDF; lSpotRate = LinearInterpolation(inIRTime, inIRRate, inMaturity); d1 = (log(inSpot / inStrike) + (lSpotRate + inSigma * inSigma / 2.0) * inMaturity) / (inSigma * sqrt(inMaturity)); d2 = d1 - inSigma * sqrt(inMaturity); lDF = exp(-lSpotRate * inMaturity); if(inCallPut == CALL){ lReturn = inSpot * NormalDistributionFunction(d1) - lDF * inStrike * NormalDistributionFunction(d2); }else if(inCallPut == PUT){ lReturn = - inSpot * NormalDistributionFunction(-d1) + lDF * inStrike * NormalDistributionFunction(-d2); } return(lReturn); }
// Returns interpolated value double CInterpolationEngine::GetInterpolatedValue( double y ) const throw(CInterpolationException) { if( m_pts.size() <= 0 || ( m_pts.size() >= MIN_SPLINE_POINTS && m_pts.size() != m_A.size() + 1 ) ) throw CInterpolationException(); if( m_pts.size() == 1 ) { // Flat interpolation return m_pts[0].f; } else { // Linear interpolation return LinearInterpolation( y ); } // else if( m_pts.size() == 2 ) // { // // Linear interpolation // return LinearInterpolation( y ); // } // else // { // // Spline interpolation // return SplineInterpolation( y ); // } }
Variant Spline::BezierInterpolation(const Vector<Variant>& knots, float t) const { if (knots.Size() == 2) { switch (knots[0].GetType()) { case VAR_FLOAT: case VAR_VECTOR2: case VAR_VECTOR3: case VAR_VECTOR4: case VAR_COLOR: case VAR_DOUBLE: return LinearInterpolation(knots[0], knots[1], t); default: return Variant::EMPTY; } } else { /// \todo Do not allocate a new vector each time Vector<Variant> interpolatedKnots; for (unsigned i = 1; i < knots.Size(); i++) { switch (knots[0].GetType()) { case VAR_FLOAT: case VAR_VECTOR2: case VAR_VECTOR3: case VAR_VECTOR4: case VAR_COLOR: case VAR_DOUBLE: interpolatedKnots.Push(LinearInterpolation(knots[i - 1], knots[i], t)); break; default: return Variant::EMPTY; } } return BezierInterpolation(interpolatedKnots, t); } }
void MurexCurve::calculate() { times_[0]=0.0; for(int i=0;i<n_-1;i++) { times_[i+1]=dc_.yearFraction(refDate_,maturities_[i]); rates_[i+1]=-log(discounts_[i])/(interpolationMode_==2 ? 1.0 : times_[i+1]); } rates_[0]=rates_[1]; interpol_=LinearInterpolation(times_.begin(),times_.end(),rates_.begin()); interpol_.update(); }
//----------------------------------------------------------------------------- Vector3 Controller::getStickState(bool Thumb, f32& KnockSize) { // つながっていなかったら処理しない if( !IsConnected() ) return Vector3( 0.0f, 0.0f, 0.0f ); // スティックの入力無視判定設定 int L_STICK_THUMB_DEAD = XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE; int R_STICK_THUMB_DEAD = XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE; /*int L_STICK_THUMB_DEAD = 32768; int R_STICK_THUMB_DEAD = 32768;*/ Vector3 dir(0.0f, 0.0f, 0.0f); XINPUT_STATE state; ZeroMemory( &state, sizeof(XINPUT_STATE) ); // 初期化 DWORD dwResult; // 関数結果判定用 dwResult = XInputGetState(_controllerNum,&state); if(dwResult == ERROR_SUCCESS){ // 情報がとれたら // trueなら左 if( Thumb ){ Vector3 StickL(0.0f,0.0f,0.0f); StickL._x = state.Gamepad.sThumbLX; StickL._z = state.Gamepad.sThumbLY; int LX = abs(StickL._x); int LY = abs(StickL._z); if( LX >= L_STICK_THUMB_DEAD || LY >= L_STICK_THUMB_DEAD){ dir = StickL; } } else // falseなら右 { Vector3 StickR(0.0f,0.0f,0.0f); StickR._x = state.Gamepad.sThumbRX; StickR._z = state.Gamepad.sThumbRY; int RX = abs(StickR._x); int RY = abs(StickR._z); if( RX >= R_STICK_THUMB_DEAD || RY >= R_STICK_THUMB_DEAD){ dir = StickR; } } } // 押し加減の計算 KnockSize = LinearInterpolation(0.0f, 1.0f, dir.length(), 32767.0f); return dir; }
Variant Spline::LinearInterpolation(const Vector<Variant>& knots, float t) const { if (knots.Size() < 2) return Variant::EMPTY; else { if (t >= 1.f) return knots.Back(); int originIndex = Clamp((int)(t * (knots.Size() - 1)), 0, (int)(knots.Size() - 2)); t = fmodf(t * (knots.Size() - 1), 1.f); return LinearInterpolation(knots[originIndex], knots[originIndex + 1], t); } }
FlatVolFactory::FlatVolFactory( Real longTermCorrelation, Real beta, const vector<Time>& times, const vector<Volatility>& vols, const Handle<YieldTermStructure>& yieldCurve, Spread displacement) : longTermCorrelation_(longTermCorrelation), beta_(beta), times_(times), vols_(vols), yieldCurve_(yieldCurve), displacement_(displacement) { volatility_ = LinearInterpolation(times_.begin(), times_.end(), vols_.begin()); volatility_.update(); registerWith(yieldCurve_); }
Variant Spline::GetPoint(float f) const { if (knots_.Size() < 2) return knots_.Size() == 1 ? knots_[0] : Variant::EMPTY; if (f > 1.f) f = 1.f; else if (f < 0.f) f = 0.f; switch (interpolationMode_) { case BEZIER_CURVE: return BezierInterpolation(knots_, f); case CATMULL_ROM_CURVE: return CatmullRomInterpolation(knots_, f); case LINEAR_CURVE: return LinearInterpolation(knots_, f); case CATMULL_ROM_FULL_CURVE: { /// \todo Do not allocate a new vector each time Vector<Variant> fullKnots; if (knots_.Size() > 1) { // Non-cyclic case: duplicate start and end if (knots_.Front() != knots_.Back()) { fullKnots.Push(knots_.Front()); fullKnots.Push(knots_); fullKnots.Push(knots_.Back()); } // Cyclic case: smooth the tangents else { fullKnots.Push(knots_[knots_.Size() - 2]); fullKnots.Push(knots_); fullKnots.Push(knots_[1]); } } return CatmullRomInterpolation(fullKnots, f); } default: URHO3D_LOGERROR("Unsupported interpolation mode"); return Variant::EMPTY; } }
Variant ValueAnimation::GetAnimationValue(float scaledTime) { unsigned index = 1; for (; index < keyFrames_.Size(); ++index) { if (scaledTime < keyFrames_[index].time_) break; } if (index >= keyFrames_.Size() || !interpolatable_ || interpolationMethod_ == IM_NONE) return keyFrames_[index - 1].value_; else { if (interpolationMethod_ == IM_LINEAR) return LinearInterpolation(index - 1, index, scaledTime); else return SplineInterpolation(index - 1, index, scaledTime); } }
void AttributeAnimation::UpdateAttributeValue(Animatable* animatable, const AttributeInfo& attributeInfo, float scaledTime) { unsigned index = 1; for (; index < keyFrames_.Size(); ++index) { if (scaledTime < keyFrames_[index].time_) break; } if (index >= keyFrames_.Size() || !interpolatable_) animatable->OnSetAttribute(attributeInfo, keyFrames_[index - 1].value_); else { if (interpolationMethod_ == IM_LINEAR) animatable->OnSetAttribute(attributeInfo, LinearInterpolation(index - 1, index, scaledTime)); else animatable->OnSetAttribute(attributeInfo, SplineInterpolation(index - 1, index, scaledTime)); } }
//----------------------------------------------------------------------------- //! 描画 //----------------------------------------------------------------------------- void Performance::DrawPerformance(Vector3 drawPos, f32& parentHeight, s64& maxFrame) { // 線形補完する _height = LinearInterpolation(0.0f, parentHeight, (f32)_totalTime, (f32)maxFrame); // 自分のバーの描画 glBegin(GL_TRIANGLE_STRIP); glColor4ubv((GLubyte*)&_drawColor); glVertex3f(drawPos._x , drawPos._y , 0.0f); glVertex3f(drawPos._x + 30.0f, drawPos._y , 0.0f); glVertex3f(drawPos._x , drawPos._y + _height, 0.0f); glVertex3f(drawPos._x + 30.0f, drawPos._y + _height, 0.0f); glEnd(); // 子のパフォーマンスの描画 for( list<Performance*>::iterator itr = _childPeform.begin(); itr != _childPeform.end(); itr++ ) { Performance* drawPef = *itr; // 描画 drawPef->DrawPerformance(drawPos, _height, _totalTime); // 次の描画位置を求める drawPos._y += drawPef->getHeight(); } }
ScaleMap::ScaleMap( const double minIn, const double maxIn, const double minOut, const double maxOut ) { setInputRange( minIn, maxIn ); setOutputRange( minOut, maxOut ); mapFunction = LinearInterpolation(); }
FdmHestonVarianceMesher::FdmHestonVarianceMesher( Size size, const boost::shared_ptr<HestonProcess> & process, Time maturity, Size tAvgSteps, Real epsilon) : Fdm1dMesher(size) { std::vector<Real> vGrid(size, 0.0), pGrid(size, 0.0); const Real df = 4*process->theta()*process->kappa()/ square<Real>()(process->sigma()); try { std::multiset<std::pair<Real, Real> > grid; for (Size l=1; l<=tAvgSteps; ++l) { const Real t = (maturity*l)/tAvgSteps; const Real ncp = 4*process->kappa()*std::exp(-process->kappa()*t) /(square<Real>()(process->sigma()) *(1-std::exp(-process->kappa()*t)))*process->v0(); const Real k = square<Real>()(process->sigma()) *(1-std::exp(-process->kappa()*t))/(4*process->kappa()); const Real qMin = 0.0; // v_min = 0.0; const Real qMax = std::max(process->v0(), k*InverseNonCentralChiSquareDistribution( df, ncp, 1000, 1e-8)(1-epsilon)); const Real minVStep=(qMax-qMin)/(50*size); Real ps,p = 0.0; Real vTmp = qMin; grid.insert(std::pair<Real, Real>(qMin, epsilon)); for (Size i=1; i < size; ++i) { ps = (1 - epsilon - p)/(size-i); p += ps; const Real tmp = k*InverseNonCentralChiSquareDistribution( df, ncp, 1000, 1e-8)(p); const Real vx = std::max(vTmp+minVStep, tmp); p = NonCentralChiSquareDistribution(df, ncp)(vx/k); vTmp=vx; grid.insert(std::pair<Real, Real>(vx, p)); } } QL_REQUIRE(grid.size() == size*tAvgSteps, "something wrong with the grid size"); std::vector<std::pair<Real, Real> > tp(grid.begin(), grid.end()); for (Size i=0; i < size; ++i) { const Size b = (i*tp.size())/size; const Size e = ((i+1)*tp.size())/size; for (Size j=b; j < e; ++j) { vGrid[i]+=tp[j].first/(e-b); pGrid[i]+=tp[j].second/(e-b); } } } catch (const Error&) { // use default mesh const Real vol = process->sigma()* std::sqrt(process->theta()/(2*process->kappa())); const Real mean = process->theta(); const Real upperBound = std::max(process->v0()+4*vol, mean+4*vol); const Real lowerBound = std::max(0.0, std::min(process->v0()-4*vol, mean-4*vol)); for (Size i=0; i < size; ++i) { pGrid[i] = i/(size-1.0); vGrid[i] = lowerBound + i*(upperBound-lowerBound)/(size-1.0); } } Real skewHint = ((process->kappa() != 0.0) ? std::max(1.0, process->sigma()/process->kappa()) : 1.0); std::sort(pGrid.begin(), pGrid.end()); volaEstimate_ = GaussLobattoIntegral(100000, 1e-4)( boost::function1<Real, Real>( compose(std::ptr_fun<Real, Real>(std::sqrt), LinearInterpolation(pGrid.begin(), pGrid.end(), vGrid.begin()))), pGrid.front(), pGrid.back())*std::pow(skewHint, 1.5); const Real v0 = process->v0(); for (Size i=1; i<vGrid.size(); ++i) { if (vGrid[i-1] <= v0 && vGrid[i] >= v0) { if (std::fabs(vGrid[i-1] - v0) < std::fabs(vGrid[i] - v0)) vGrid[i-1] = v0; else vGrid[i] = v0; } } std::copy(vGrid.begin(), vGrid.end(), locations_.begin()); for (Size i=0; i < size-1; ++i) { dminus_[i+1] = dplus_[i] = vGrid[i+1] - vGrid[i]; } dplus_.back() = dminus_.front() = Null<Real>(); }
//----------------------------------------------------------------------------- //! 狙う相手を探して設定 //! @return true:敵を設定完了 false:狙う敵はいない //----------------------------------------------------------------------------- bool AllyHealer::searchAndSetTarget() { Player* pPlayer = IObjDataManager()->_pPlayer; // 前の情報があったらかつ、死亡していなければ if( _pPrevTarget != nullptr && !_pPrevTarget->isDead() ) { f32 lengthToTarget = getLengthtoTarget(_pPrevTarget); // 捜索範囲内なら static const f32 searchLength = 200.0f; if( lengthToTarget < searchLength ) { // 検索しない return true; } } // 最初はプレイヤー _target = pPlayer; // 味方データから一番体力の少ない味方を割り出す vector<AllyBase*>::iterator itr; // プレイヤーの体力 Status::Param* playerParam = IObjDataManager()->_pPlayer->getStatus()->getParam(); f32 PlayerHP = playerParam->_HP; f32 PlayerHPMAX = playerParam->_HPMAX; s32 playerSeverity = (s32)( LinearInterpolation( (f32)(_SeverityMax) , 0, PlayerHP, PlayerHPMAX) ); // 緊急度 s32 Severity = playerSeverity; // すべてのHPを検査、緊急度をチェック for( itr = IObjDataManager()->_pAllyData.begin(); itr != IObjDataManager()->_pAllyData.end(); itr++) { AllyBase* ally = *itr; // 死亡していたら処理しない if( ally->isDead() ) continue; Status::Param* allyParam = ally->getStatus()->getParam(); f32 HP = allyParam->_HP; f32 HPMAX = allyParam->_HPMAX; // 今回の緊急度 s32 nowSeverity = (s32)LinearInterpolation((f32)_SeverityMax, 0, HP, HPMAX); // 今回の緊急度が高かったら if( Severity < nowSeverity ) { // 今回で更新 Severity = nowSeverity; _target = ally; } } // 一番近い敵をターゲットに設定 if( _target != nullptr ) { // 次回用ターゲットに設定しておく _pPrevTarget = _target; // 一番近いやつをターゲットにする _key->setTarget(_target); }else{ return false; } return true; }
void FFTEngine::precalculate(const std::vector<boost::shared_ptr<Instrument> >& optionList) { // Group payoffs by expiry date // as with FFT we can compute a bunch of these at once resultMap_.clear(); typedef std::vector<boost::shared_ptr<StrikedTypePayoff> > PayoffList; typedef std::map<Date, PayoffList> PayoffMap; PayoffMap payoffMap; for (std::vector<boost::shared_ptr<Instrument> >::const_iterator optIt = optionList.begin(); optIt != optionList.end(); optIt++) { boost::shared_ptr<VanillaOption> option = boost::dynamic_pointer_cast<VanillaOption>(*optIt); QL_REQUIRE(option, "instrument must be option"); QL_REQUIRE(option->exercise()->type() == Exercise::European, "not an European Option"); boost::shared_ptr<StrikedTypePayoff> payoff = boost::dynamic_pointer_cast<StrikedTypePayoff>(option->payoff()); QL_REQUIRE(payoff, "non-striked payoff given"); payoffMap[option->exercise()->lastDate()].push_back(payoff); } std::complex<Real> i1(0, 1); Real alpha = 1.25; for (PayoffMap::const_iterator payIt = payoffMap.begin(); payIt != payoffMap.end(); payIt++) { Date expiryDate = payIt->first; // Calculate n large enough for maximum strike, and round up to a power of 2 Real maxStrike = 0.0; for (PayoffList::const_iterator it = payIt->second.begin(); it != payIt->second.end(); it++) { boost::shared_ptr<StrikedTypePayoff> payoff = *it; if (payoff->strike() > maxStrike) maxStrike = payoff->strike(); } Real nR = 2.0 * (std::log(maxStrike) + lambda_) / lambda_; Size log2_n = (static_cast<Size>((std::log(nR) / std::log(2.0))) + 1); Size n = 1 << log2_n; // Strike range (equation 19,20) Real b = n * lambda_ / 2.0; // Grid spacing (equation 23) Real eta = 2.0 * M_PI / (lambda_ * n); // Discount factor Real df = discountFactor(expiryDate); Real div = dividendYield(expiryDate); // Input to fourier transform std::vector<std::complex<Real> > fti; fti.resize(n); // Precalculate any discount factors etc. precalculateExpiry(expiryDate); for (Size i=0; i<n; i++) { Real k_u = -b + lambda_ * i; Real v_j = eta * i; Real sw = eta * (3.0 + ((i % 2) == 0 ? -1.0 : 1.0) - ((i == 0) ? 1.0 : 0.0)) / 3.0; std::complex<Real> psi = df * complexFourierTransform(v_j - (alpha + 1)* i1); psi = psi / (alpha*alpha + alpha - v_j*v_j + i1 * (2 * alpha + 1.0) * v_j); fti[i] = std::exp(i1 * b * v_j) * sw * psi; } // Perform fft std::vector<std::complex<Real> > results(n); FastFourierTransform fft(log2_n); fft.transform(fti.begin(), fti.end(), results.begin()); // Call prices std::vector<Real> prices, strikes; prices.resize(n); strikes.resize(n); for (Size i=0; i<n; i++) { Real k_u = -b + lambda_ * i; prices[i] = (std::exp(-alpha * k_u) / M_PI) * results[i].real(); strikes[i] = std::exp(k_u); } for (PayoffList::const_iterator it = payIt->second.begin(); it != payIt->second.end(); it++) { boost::shared_ptr<StrikedTypePayoff> payoff = *it; Real callPrice = LinearInterpolation(strikes.begin(), strikes.end(), prices.begin())(payoff->strike()); switch (payoff->optionType()) { case Option::Call: resultMap_[expiryDate][payoff] = callPrice; break; case Option::Put: resultMap_[expiryDate][payoff] = callPrice - process_->x0() * div + payoff->strike() * df; break; default: QL_FAIL("Invalid option type"); } } } }