Пример #1
0
void
test1(int denom)
{
    double r1, r2;
    int t1, t2;
    
    r1 = recip(denom); /* Stored in memory */
    r2 = recip(denom); /* Stored in register */
    t1 = r1 == r2;     /* Compares register to memory */
    do_nothing();      /* Forces register save to memory */
    t2 = r1 == r2;     /* Compares memory to memory */
    printf("test1 t1: r1 %f %c= r2 %f\n", r1, t1 ? '=' : '!', r2);
    printf("test1 t2: r1 %f %c= r2 %f\n", r1, t2 ? '=' : '!', r2);
}
Пример #2
0
doubledouble erf(const doubledouble x) {
  if (0.0==x.h()) return 0.0;
  int i; doubledouble y,r;
  // const below is evalf(1/sqrt(Pi),40)
  static const doubledouble oneonrootpi="0.564189583547756286948079451560772585844";
  const double cut=1.5;  // switch to continued fraction here
  y=fabs(x);
  if (y.h()>26.0) { // erf is +or- 1 to 300 dp.
    r=1;
  } else if (y.h()<cut) { // use power series
    doubledouble ap=0.5,s,t,x2;
    s=t=2.0; x2=sqr(x);
    for (i=0; i<200; i++) {
      ap+=1;
      t*=x2/ap;
      s+=t;
      if (fabs(t.h())<1e-35*fabs(s.h())) {
        r=x*oneonrootpi*s/exp(x2);
	break;
      }
    }
    if (i>199) 
      { cerr<<"\ndoubledouble: no convergence in erf power series, x="<<x<<endl; exit(1); }
  } else { // |x|>=cut, use continued fraction, Lentz method
    double an,small=1e-300;
    doubledouble b,c,d,h,del,x2;
    x2=sqr(x);
    b=x2+0.5;
    c=1.0e300;
    d=recip(b);
    h=d;
    for (i=1; i<300; i++) {
      an=i*(0.5-i);
      b+=2.0;
      d=an*d+b;
      if (fabs(d.h())<small) d=small;
      c=b+an/c;
      if (fabs(c.h())<small) c=small;
      d=recip(d);
      del=d*c;
      h*=del;
      if (del.h()==1.0 && del.l()<1.0e-30) break;
      if (299==i)
        { cerr<<"\ndoubledouble: no convergence in erf continued fraction, x="<<x<<endl; exit(1); }
    }
    r=1.0-oneonrootpi*sqrt(x2)/exp(x2)*h;
  } 
  if (x.h()>0.0) return r; else return -r;
}
Пример #3
0
Файл: ct.c Проект: EdKeith/core
static A jttayamp(J jt,A w,B nf,A x,A h){A y;B ng=!nf;I j,n;V*v=VAV(h);
 ASSERT(AR(x)<=(nf?v->lr:v->rr),EVRANK);
 switch(v->id){
  case CPLUS:  R tpoly(over(x,one));
  case CMINUS: R tpoly(nf?over(x,num[-1]):over(negate(x),one));
  case CSTAR:  R tpoly(over(zero,x));
  case CDIV:   ASSERT(ng,EVDOMAIN); R tpoly(over(zero,recip(x)));
  case CJDOT:  R tpoly(nf?over(x,a0j1):over(jdot1(x),one));
  case CPOLY:  ASSERT(nf,EVDOMAIN); R tpoly(BOX&AT(x)?poly1(x):x);
  case CHGEOM: ASSERT(nf,EVDOMAIN); RE(j=i0(x)); ASSERT(0<=j,EVDOMAIN);
               y=IX(j);
               R tpoly(divide(hgcoeff(y,h),fact(y)));
  case CBANG:  ASSERT(nf,EVDOMAIN); RE(j=i0(x)); ASSERT(0<=j,EVDOMAIN); 
               R tpoly(divide(poly1(box(iota(x))),fact(x)));
  case CEXP:   if(nf)R eva(x,"(^.x)&^ % !");
               RE(n=i0(x));   
               R 0<=n?tpoly(over(reshape(x,zero),one)):atop(ds(CDIV),amp(h,sc(-n))); 
  case CFIT:   ASSERT(nf&&CPOLY==ID(v->f),EVDOMAIN);
               y=over(x,IX(IC(x)));
               R tpoly(mdiv(df2(x,y,h),atab(CEXP,y,IX(IC(x)))));
  case CCIRCLE:
   switch(i0(x)){
    case 1:    R eval("{&0 1 0 _1@(4&|) % !");
    case -3:   R eval("{&0 1 0 _1@(4&|) % ]");
    case 2:    R eval("{&1 0 _1 0@(4&|) % !");
    case 5:    R eval("2&|    % !");
    case -7:   R eval("2&|    % ]");
    case 6:    R eval("2&|@>: % !");
    case -1:   R eval("(2&|              % ]) * ([: */ (1&+ % 2&+)@(i.@<.&.-:))\"0");
    case -5:   R eval("({&0 1 0 _1@(4&|) % ]) * ([: */ (1&+ % 2&+)@(i.@<.&.-:))\"0");
 }}
 ASSERT(0,EVDOMAIN);
}
Пример #4
0
void
test2(int denom)
{
    double r1;
    int t1;
    
    r1 = recip(denom);
    t1 = r1 == 1.0 / (double) denom;
    printf("test2 t1: r1 %f %c= 1.0/10.0\n", r1, t1 ? '=' : '!');
}
Пример #5
0
doubledouble atan(const doubledouble& x) {
  double xh=x.h();
  if (0.0==xh) return doubledouble(0.0);
  // Asymptotic formula for large |x|...
  if (fabs(xh)>1.0e6) 
    { doubledouble r=recip(x), r2=sqr(r); return doubledouble::Pion2-r+r2*r*(1.0-"0.6"*r2)/3; }
  doubledouble s,c,a=atan(xh); // a=double approx to result
  sincos(a,s,c);
  return a+c*(c*x-s);  // Newton step
}
Пример #6
0
// doubledouble^int
doubledouble powint(const doubledouble& u, const int c) {
  if (c<0) return recip(powint(u,-c));
  switch (c) {
    case 0: return u.h()==0.0?doubledouble(pow(0.0,0.0)):doubledouble(1.0); // let math.h handle 0^0.
    case 1: return u;  
    case 2: return sqr(u);
    case 3: return sqr(u)*u;
    default: { // binary method
      int n=c, m; doubledouble y=1.0, z=u; if (n<0) n=-n;
      while (1) {
        m=n; n/=2;
        if (n+n!=m) { // if m odd
           y*=z; if (0==n) return y;
        }
        z=sqr(z); 
      }
    }
  }
}
Line getPerpendic(Line line, Point at) {
    Line newLine;
    // if vertical newLine => horizontal
    if (line.a == 0){       // y=0; x=c
        newLine.a = 1;
        newLine.b = 0;
        newLine.c = at.y();
    }else{
        if (line.b == 0) {  // x=0; y=c
            newLine.a = 0;
            newLine.b = 1;
            newLine.c = at.x();
        }else{
            newLine.a = 1.0;
            newLine.b = -1*recip(-1*line.b);    // Find the reciprocal of line
            newLine.c = at.y() + newLine.b*at.x();       // Calculate the equation through the point 'at'
        }
    }
    return newLine;
}
Пример #8
0
int main() {
  Lattice lat(Cartesian(0,.5,.5), Cartesian(.5,0,.5), Cartesian(.5,.5,0));
  Cartesian middle(0.5,0.5,0.5);
  Relative middlerel = lat.toRelative(middle);
  Reciprocal recip(0.2,0,0);
  int resolution = 20;
  Grid foo(lat, resolution, resolution, resolution),
    bar(lat, resolution, resolution, resolution);
  foo.Set(gaussian);
  foo.epsSlice("demo.eps", Cartesian(1,0,0), Cartesian(0,1,0),
               Cartesian(-.5,-.5,.5), 150);
  foo.epsNativeSlice("native.eps", Cartesian(1,0,0), Cartesian(0,1,0),
                     Cartesian(-.5,-.5,.5));
  
  //std::cout << "and here is the foo" << (foo + 2*bar + foo.cwise()*bar);
  std::cout << "middle and middlerel are:\n"
            << middle << std::endl << middlerel << std::endl
            << lat.toCartesian(middlerel) << std::endl;
  std::cout << "middle dot recip: " << recip * middle << std::endl;
  return 0;
}
Пример #9
0
/** 
 * Exact polynomial division of a, b \in Z_p[x_0, \ldots, x_n]
 * It doesn't check whether the inputs are proper polynomials, so be careful
 * of what you pass in.
 *  
 * @param a  first multivariate polynomial (dividend)
 * @param b  second multivariate polynomial (divisor)
 * @param q  quotient (returned)
 * @param var variables X iterator to first element of vector of symbols
 *
 * @return "true" when exact division succeeds (the quotient is returned in
 *          q), "false" otherwise.
 * @note @a p = 0 means the base ring is Z
 */
bool divide_in_z_p(const ex &a, const ex &b, ex &q, const exvector& vars, const long p)
{
	static const ex _ex1(1);
	if (b.is_zero())
		throw(std::overflow_error("divide_in_z: division by zero"));
	if (b.is_equal(_ex1)) {
		q = a;
		return true;
	}
	if (is_exactly_a<numeric>(a)) {
		if (is_exactly_a<numeric>(b)) {
			// p == 0 means division in Z
			if (p == 0) {
				const numeric tmp = ex_to<numeric>(a/b);
				if (tmp.is_integer()) {
					q = tmp;
					return true;
				} else
					return false;
			} else {
				q = (a*recip(ex_to<numeric>(b), p)).smod(numeric(p));
				return true;
			}
		} else
			return false;
	}
	if (a.is_equal(b)) {
		q = _ex1;
		return true;
	}

	// Main symbol
	const ex &x = vars.back();

	// Compare degrees
	int adeg = a.degree(x), bdeg = b.degree(x);
	if (bdeg > adeg)
		return false;

	// Polynomial long division (recursive)
	ex r = a.expand();
	if (r.is_zero())
		return true;
	int rdeg = adeg;
	ex eb = b.expand();
	ex blcoeff = eb.coeff(x, bdeg);
	exvector v;
	v.reserve(std::max(rdeg - bdeg + 1, 0));
	exvector rest_vars(vars);
	rest_vars.pop_back();
	while (rdeg >= bdeg) {
		ex term, rcoeff = r.coeff(x, rdeg);
		if (!divide_in_z_p(rcoeff, blcoeff, term, rest_vars, p))
			break;
		term = (term*power(x, rdeg - bdeg)).expand();
		v.push_back(term);
		r = (r - term*eb).expand();
		if (p != 0)
			r = r.smod(numeric(p));
		if (r.is_zero()) {
			q = (new add(v))->setflag(status_flags::dynallocated);
			return true;
		}
		rdeg = r.degree(x);
	}
	return false;
}
void CContextContactsDetailView::HandleCreateMessageL()
{
	TInt idx = iContainer->get_current_item_idx();
	
	const MPbkFieldData& fielddata=iItem->PbkFieldAt(idx);
	TPbkFieldId id = fielddata.PbkFieldId();
	const TPbkContactItemField * field = iItem->FindField(id, idx);
	
	TAddressSelectorF selector = SmsSelectorL;
	TMessageSenderF sender = &CMessaging::MessageSenderL;
	TPbkFieldFilterF filter = SmsFieldFilterL;
	TInt warningResource = R_CONTACTS_NO_SMS;
	
	auto_ptr<CArrayFixFlat<TUid> > disabled_mtms( new (ELeave) CArrayFixFlat< TUid >(4) );

	const CPbkFieldInfo &info=field->FieldInfo();
	TBool is_address_field=EFalse;
	auto_ptr<CDesCArrayFlat> recip( new (ELeave) CDesCArrayFlat(1));
	auto_ptr<CDesCArrayFlat> alias( new (ELeave) CDesCArrayFlat(1));
	
	auto_ptr<HBufC> title(iItem->GetContactTitleL());
	alias->AppendL(*title);
	
	if (!info.IsPhoneNumberField()) {
		disabled_mtms->AppendL(KSenduiMtmSmsUid);
	} else {
		is_address_field=ETrue;
	}
	if (!info.IsPhoneNumberField() && !info.IsMmsField() ) {
		disabled_mtms->AppendL(KSenduiMtmMmsUid);
	} else {
		is_address_field=ETrue;
	}
	if (!info.IsEmailField()) {
		disabled_mtms->AppendL(KSenduiMtmSmtpUid);
	} else {
		is_address_field=ETrue;
	}
	
	if (!is_address_field) disabled_mtms->Reset();
	else recip->AppendL( fielddata.PbkFieldText() );
	disabled_mtms->AppendL(KSenduiMtmIrUid);
	disabled_mtms->AppendL(KSenduiMtmBtUid);
	
	TUid mtm=iMessaging->iSendAppUi->ShowSendQueryL(0,  TSendingCapabilities(KCapabilitiesForAllServices), 
		disabled_mtms.get(), _L("Send Message"));
		
	if (mtm==KNullUid) return;
	
	if (is_address_field) {
		iMessaging->MessageSenderL(recip.get(), alias.get(), mtm);
	} else {
		if (mtm==KSenduiMtmSmtpUid) {
			selector=EmailSelectorL;
			filter=EmailFieldFilterL;
			warningResource=R_CONTACTS_NO_EMAIL;
		} else if (mtm!=KSenduiMtmSmsUid) {
			selector=MmsSelectorL;
			filter=MmsFieldFilterL;
			warningResource=R_CONTACTS_NO_MMS;
		}
		iMessaging->CreateSingleMessageL( iItem->Id(), selector, sender, mtm );
	}
	
}
static inline void SV_PackEntity( 
	int edictIdx, 
	edict_t* ent, 
	SendTable* pSendTable,
	EntityChange_t changeType, 
	CFrameSnapshot *pSnapshot )
{
	int iSerialNum = pSnapshot->m_Entities[ edictIdx ].m_nSerialNumber;

	// Check to see if this entity specifies its changes.
	// If so, then try to early out making the fullpack
	bool bUsedPrev = false;
	if ( changeType == ENTITY_CHANGE_NONE )
	{
		// Now this may not work if we didn't previously send a packet;
		// if not, then we gotta compute it
		bUsedPrev = framesnapshot->UsePreviouslySentPacket( pSnapshot, edictIdx, iSerialNum );
	}
					  
	if ( !bUsedPrev || sv_debugmanualmode.GetInt() )
	{
		// First encode the entity's data.
		char packedData[MAX_PACKEDENTITY_DATA];
		bf_write writeBuf( "SV_PackEntity->writeBuf", packedData, sizeof( packedData ) );
		
		// (avoid constructor overhead).
		unsigned char tempData[ sizeof( CSendProxyRecipients ) * MAX_DATATABLE_PROXIES ];
		CUtlMemory< CSendProxyRecipients > recip( (CSendProxyRecipients*)tempData, pSendTable->GetNumDataTableProxies() );

		if( !SendTable_Encode( pSendTable, ent->m_pEnt, &writeBuf, NULL, edictIdx, &recip ) )
		{							 
			Host_Error( "SV_PackEntity: SendTable_Encode returned false (ent %d).\n", edictIdx );
		}

		SV_EnsureInstanceBaseline( edictIdx, packedData, writeBuf.GetNumBytesWritten() );
			
		int nFlatProps = SendTable_GetNumFlatProps( pSendTable );
		IChangeFrameList *pChangeFrame;

		// If this entity was previously in there, then it should have a valid IChangeFrameList 
		// which we can delta against to figure out which properties have changed.
		//
		// If not, then we want to setup a new IChangeFrameList.
		PackedEntity *pPrevFrame = framesnapshot->GetPreviouslySentPacket( edictIdx, pSnapshot->m_Entities[ edictIdx ].m_nSerialNumber );
		if ( pPrevFrame )
		{
			// Calculate a delta.
			bf_read bfPrev( "SV_PackEntity->bfPrev", pPrevFrame->LockData(), pPrevFrame->GetNumBytes() );
			bf_read bfNew( "SV_PackEntity->bfNew", packedData, writeBuf.GetNumBytesWritten() );
			
			int deltaProps[MAX_DATATABLE_PROPS];

			int nChanges = SendTable_CalcDelta(
				pSendTable, 
				pPrevFrame->LockData(), pPrevFrame->GetNumBits(),
				packedData,	writeBuf.GetNumBitsWritten(),
				
				deltaProps,
				ARRAYSIZE( deltaProps ),

				edictIdx
				);

			// If it's non-manual-mode, but we detect that there are no changes here, then just
			// use the previous pSnapshot if it's available (as though the entity were manual mode).
			// It would be interesting to hook here and see how many non-manual-mode entities 
			// are winding up with no changes.
			if ( nChanges == 0 )
			{
				if ( changeType == ENTITY_CHANGE_NONE )
				{
					for ( int iDeltaProp=0; iDeltaProp < nChanges; iDeltaProp++ )
					{
						Msg( "Entity %d (class '%s') reported ENTITY_CHANGE_NONE but '%s' changed.\n", 
							edictIdx,
							STRING( ent->classname ),
							pSendTable->GetProp( deltaProps[iDeltaProp] )->GetName() );

					}
				}
				else
				{
					if ( pPrevFrame->CompareRecipients( recip ) )
					{
						if ( framesnapshot->UsePreviouslySentPacket( pSnapshot, edictIdx, iSerialNum ) )
							return;
					}
				}
			}
		
			// Ok, now snag the changeframe from the previous frame and update the 'last frame changed'
			// for the properties in the delta.
			pChangeFrame = pPrevFrame->SnagChangeFrameList();
			
			ErrorIfNot( pChangeFrame && pChangeFrame->GetNumProps() == nFlatProps,
				("SV_PackEntity: SnagChangeFrameList returned null")
			);

			pChangeFrame->SetChangeTick( deltaProps, nChanges, pSnapshot->m_nTickNumber );
		}
		else
		{
			// Ok, init the change frames for the first time.
			pChangeFrame = AllocChangeFrameList( nFlatProps, pSnapshot->m_nTickNumber );
		}

		// Now make a PackedEntity and store the new packed data in there.
		PackedEntity *pCurFrame = framesnapshot->CreatePackedEntity( pSnapshot, edictIdx );
		pCurFrame->SetChangeFrameList( pChangeFrame );
		pCurFrame->m_nEntityIndex = edictIdx;
		pCurFrame->m_pSendTable = pSendTable;
		pCurFrame->AllocAndCopyPadded( packedData, writeBuf.GetNumBytesWritten(), &g_PackedDataAllocator );
		pCurFrame->SetRecipients( recip );
	}
}
Пример #12
0
doubledouble cosh(const doubledouble& x) { doubledouble t=exp(x); return 0.5*(t+recip(t)); }
Пример #13
0
// hyperbolic
doubledouble sinh(const doubledouble& x) { 
  if (fabs(x.h())<1.0e-5) { // avoid cancellation in e^x-e^(-x), use Taylor series...
    doubledouble q=sqr(x);  return x*(1+q/6*(1+q/20*(1+q/42))); }
  doubledouble t=exp(x); 
  return 0.5*(t-recip(t)); 
}
Пример #14
0
matrix_pf * NullSpace(BerlekampMatrix* b_mtx, int *r_ret)
{
  int deg = b_mtx->GetDegree();
  int prime_char = b_mtx->PrimeBase();
  matrix_pf *v = new matrix_pf(0,deg,0,deg);
  int *c = new int[deg];
  PrimeFieldElem b_val;
  int i, j, k, k1, r, s;
  bool dependence_found;

  for(i=0; i<deg; i++) c[i]=-1;
  r=0;

  for( k=0; k<deg; k++)
    {
    dependence_found = false;

    for( j=0; j<deg; j++)
      {
      if( (*b_mtx)[k][j] == 0 ) continue;
        if( c[j] >= 0 ) continue;

          //---------------------------------
          //  multiply column by -1/B[k,j]
          b_val = neg(recip( (*b_mtx)[k][j]));
          for( k1=0; k1<deg; k1++)
            (*b_mtx)[k1][j] *= b_val;

          //---------------------------------------
          // add B[k,i] times column j to column i
          // for all i .ne. j

          for( i=0; i<deg; i++)
            {
            if( (i==j) || ((*b_mtx)[k][i] == 0) ) continue;
              b_val = (*b_mtx)[k][i];
              for( k1=0; k1<deg; k1++)
                {
                (*b_mtx)[k1][i] += b_val * (*b_mtx)[k1][j];
                }
            }
          c[j] = k;
          dependence_found = true;
          break;
      } // end of loop over j
    if( !dependence_found )
      {
      for( j=0; j<deg; j++)
        {
        (*v)[r][j] = PrimeFieldElem(prime_char,0);
        for( s=0; s<deg; s++)
          {
          if( c[s] == j ) (*v)[r][j] = (*b_mtx)[k][s];
          }
        if( j==k ) (*v)[r][j] = PrimeFieldElem(prime_char,1);
        }
      r++;
      }
    } // end of loop over k
  *r_ret = r;
  return(v);
};
Пример #15
0
Файл: foo2.C Проект: 8l/rose
int main(int, char**) {
  int x = 3;
  return int(int(www) * recip(x));
}
Пример #16
0
 // Newton-Raphson refinements of the low-precision ops
 vr recip2(const vr &a) { vr b=recip(a); return (imm(2)-a*b)*b; }