Exemple #1
0
int main()
 {
  fraction a(4,3);
  fraction b(5,4);

  std::cout 
   << "a=" << a << std::endl
   << "b=" << b << std::endl
   << "~a=" << ~a << std::endl
   << "~b=" << ~b << std::endl
   << "4+a=" << 4+a << std::endl
   << "a+4=" << a+4 << std::endl
   << "4-a=" << 4-a << std::endl
   << "a-4=" << a-4 << std::endl
   << "a+b=" << a+b << std::endl
   << "a-b=" << a-b << std::endl
   << "a*b=" << a*b << std::endl
   << "a*3=" << a*3 << std::endl
   << "11*a=" << 11*a << std::endl
   << "a/b=" << a/b << std::endl
   << "7/a=" << 7/a << std::endl
   << "a/9=" << a/9 << std::endl
   ;

  // 3/7
  std::cout << fraction(3,4)*fraction(4,5)*fraction(5,6)*fraction(6,7) << std::endl;
  return 0;
 }
Exemple #2
0
void deriv705a (const range &r, char *task, char answ[][BUFSZ], char *src)
{
    char buf[20][BUFSZ];
    int a,bc,bd,c;
    do {
        a = rndr(r);
        bc = rndr(r);
        bd = rndr(r);
        c = rndr(r);
    } while (!(a!=0 && bc<bd && bc>0 && bd>0 && (bc*bc)%(bd*bd)!=0));

    strcpy(task, "");
    catprintf(task, "String(\"Найдите производную указанной функции:\")");
    catprintf(task, "\ny(x)=((%s)/(%s)^2)*arcsin(%s)",
        polynomial(buf[0],2,
            1, chprintf(buf[1],"arctg(%s)", memb(buf[2], 1,a,1,1,"x",false)),
            c, ""
        ),
        polynomial(buf[3],2, a*a,"",1,"x^2"),
        fraction(buf[4], bc,1,bd)
    );
    sprintf(src, "y(x)=((arctg(x/a))/((a^2+x^2)^2))*arcsin(b)");

    sprintf(answ[0], "y(x)`=((%s)/((%s)^3))*arcsin(%s)",
        polynomial(buf[0],2,
            a,"",
            -4,polynomial(buf[1],2,
                1,chprintf(buf[2],"x*arctg(%s)", memb(buf[3],1,a,1,1,"x",false)),
                -c,"x"
               )
        ),
        polynomial(buf[4],2, a*a,"", 1,"x^2"),
        fraction(buf[5], bc,1,bd)
    );
    sprintf(answ[1], "y(x)`=((%s)/((%s)^4))*arcsin(%s)",
        polynomial(buf[0],2,
            a,"",
            -2,polynomial(buf[1],2, 1,chprintf(buf[2],"x*arctg(%s)", memb(buf[3],1,a,1,1,"x",false)), -c,"x")
        ),
        polynomial(buf[4],2, a*a,"", 1,"x^2"),
        fraction(buf[5], bc,1,bd)
    );
    sprintf(answ[2], "y(x)`=((%s)/((%s)^3))*arcsin(%s)",
        polynomial(buf[0],2,
            a*a,"",
            -4,polynomial(buf[1],2, 1,chprintf(buf[2],"x^2*arctg(%s)", memb(buf[3],1,a,1,1,"x",false)), -c,"x^2")
        ),
        polynomial(buf[4],2, a*a,"", 1,"x^2"),
        fraction(buf[5], bc,1,bd)
    );
    sprintf(answ[3], "y(x)`=((%s)/(sqrt(1-%s)*(%s)^4))",
        polynomial(buf[0],2,
            a,"",
            -2,polynomial(buf[1],2, 1,chprintf(buf[2],"x*arctg(%s)", memb(buf[3],1,a,1,1,"x",false)), -c,"x")
        ),
        fraction(buf[5], bc*bc,1,bd*bd),
        polynomial(buf[4],2, a*a,"", 1,"x^2")
    );
}
fraction fraction::operator /(const fraction& a) const
{
    int tmpNumerator=numerator*a.denominator;
    int tmpDenominator=denominator*a.numerator;
    int GCD;
    GCD=GreatestCommonDivisor(tmpNumerator,tmpDenominator);
    if(GCD==1)
    return fraction(tmpNumerator,tmpDenominator);
    else
        return fraction(tmpNumerator/GCD,tmpDenominator/GCD);
}
Exemple #4
0
const fraction operator*(const fraction &a, int64_t b) {
  if(b < a.getInterimMultOverflowPt()) {
    //   b < interimMultOverflowPt
    return fraction(b * a.getNumer(), a.getDenom());
  } else if(b <= a.getFinalMultOverflowPt()) {
    //   interimMultOverflowPt <= b <= finalMultInterimPt
    cerr << "fraction::operator*- an interim overflow has occurred\n";
    return fraction(I64_MAX);
  } else {  //  finalMultInterimPt < b
    cerr << "fraction::operator*- a final overflow has occurred\n";
    return fraction(I64_MAX);
  }
}
Exemple #5
0
char *product(void){
	char *var1, *var2;
	var1 = fraction();
	while(match(TIMES)){
		advance();
		var2 = fraction();
		//printf("%s = %s * %s\n", var1,var1,var2);
		//printf("IMUL %s, %s\n", var2, var1);
        fprintf(f,"IMUL %s, %s\n", var2, var1);
		freename(var2);
	}

	return var1;
}
Exemple #6
0
int main()
{
	fraction a=fraction(5,9);
	fraction b=fraction(2,3);
	fraction c;
	printf("a = %d/%d\n",a.p,a.q);
	printf("b = %d/%d\n",b.p,b.q);
	c=a+b;
	printf("c = %d/%d\n",c.p,c.q);
	c=a-b;
	printf("c = %d/%d\n",c.p,c.q);
	a+=b;
	printf("a = %d/%d\n",a.p,a.q);
	return 0;
}
angle_parser::angle_parser(const std::string& xms) {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "parse angle spec: %s", xms.c_str());
	astro::regex	regex;
	try {
		regex = astro::regex(r, astro::regex::extended);
	} catch (const std::exception& x) {
		debug(LOG_DEBUG, DEBUG_LOG, 0, "regex exception: %s %s",
			typeid(x).name(), x.what());
		throw;
	}
	astro::smatch	matches;
	if (!regex_match(xms, matches, regex)) {
		std::string	msg = stringprintf("bad angle spec '%s'",
			xms.c_str());
		debug(LOG_DEBUG, DEBUG_LOG, 0, "%s", msg.c_str());
		throw std::runtime_error(msg);
	}

#if 0
	for (int i = 0; i < 12; i++) {
		debug(LOG_DEBUG, DEBUG_LOG, 0, "matches[%d]: %d %d '%s'",
			i, matches.position(i), matches.length(i),
			std::string(matches[i]).c_str());
	}
#endif

	// initialization
	_value = 0;

	// handle the case of decimal number
	_value += integer(matches, 2);
	_value += fraction(matches, 4);

	// separate minutes field
	_value += integer(matches, 6) / 60.;

	// with fractional part
	_value += fraction(matches, 8) / 60.;

	// separate seconds field
	_value += integer(matches, 10) / 3600.;
	_value += fraction(matches, 11) / 3600.;

	// add sign
	_value *= sign(matches, 1);
	debug(LOG_DEBUG, DEBUG_LOG, 0, "parsed value: %s -> %f", xms.c_str(),
		_value);
}
Exemple #8
0
//各种操作
fraction operator+(const fraction&a, const fraction&b)
{
	/*fraction m(a.numerator*b.denominator, a.denominator*b.denominator);
	fraction n(b.numerator*a.denominator, a.denominator*b.denominator);*/
	return fraction(a.numerator*b.denominator+ b.numerator*a.denominator, a.denominator*b.denominator);

}
fraction fraction::operator -(const fraction& a) const
{
    int tmpNumerator;
    int tmpDenominator;
    int GCD;
    int cnt1,cnt2;
    tmpDenominator=LeastCommonMultiple(denominator,a.denominator);
    cnt1=tmpDenominator/denominator;
    cnt2=tmpDenominator/a.denominator;
    tmpNumerator=cnt1*numerator-cnt2*a.numerator;
    GCD=GreatestCommonDivisor(tmpNumerator,tmpDenominator);
    if(GCD==1)
    return fraction(tmpNumerator,tmpDenominator);
    else
    return fraction(tmpNumerator/GCD,tmpDenominator/GCD);
}
struct fraction_precision closest_fraction(double r, int steps,
                                           int (*callback) (struct
                                                            fraction_precision))
{
    const double    x = r > 0 ? r : -r;
    struct fraction_precision loop = { x, 1, 0 }, best = loop, optimum = loop;

    while (steps--) {
        double          y = fraction(loop);

        loop.precision = x == y ? 9999 : -log10((y > x ? y / x : x / y) - 1);

        if (loop.precision > best.precision) {
            if (callback != NULL && quality(loop) > quality(optimum)) {
                steps = (*callback) (optimum = loop);
            }
            best = loop;
        }
#if NAIVE_SLOW_ALGORITHM                   /* Easy to understand */
        (y < x) ? ++loop.n : ++loop.d;
#else                                      /* harder but MUCH faster */
        (x > 1) ? (loop.n = x * ++loop.d + 0.5) : (loop.d = ++loop.n / x + 0.5);
#endif
    }
    return best;
}
Exemple #11
0
TDuration& TDuration::operator+=(const TDuration& t)
      {
      Fraction f1 = fraction() + t.fraction();
      TDuration d(f1);
      _val  = d._val;
      _dots = d._dots;
      return *this;
      }
Exemple #12
0
void deriv415a (const range &r, char *task, char answ[][BUFSZ], char *src)
{
    char buf[20][BUFSZ];
    int a, b, c;
    do {
        a = rndr(r);
        b = rndr(r);
        c = rndr(r);
    } while (!(a>1 && b>0));

    strcpy(task, "");
    catprintf(task, "String(\"Найдите производную указанной функции:\")");
    catprintf(task, "\ny(x)=arcsin(sqrt(%d/x))+arctg(%d)", b,c);

    sprintf(answ[0], "y(x)`=-(%s/(2*x*sqrt(%s)))",fraction(buf[0],1,b,1),polynomial(buf[1],2,1,"x",-b,""));
    sprintf(answ[1], "y(x)`=(%s)/(2*sqrt(%s))",polynomial(buf[0],1,b,"x"),polynomial(buf[1],2,1,"x",-b,""));
    sprintf(answ[2], "y(x)`=(%d)/(2*x^2*sqrt(1-(%d)/x))+arctg(%d)",-b,b,c);
    sprintf(answ[0], "y(x)`=-(%s/(2*x*sqrt(%s)))+(%s)",fraction(buf[0],1,b,1),polynomial(buf[1],2,1,"x",-b,""), fraction(buf[2],1,1,1+c*c));
}
Exemple #13
0
			fraction get_reduce() const
			{
				const value_type gcd_value =
					gcd(numerator, denominator);

				assert((denominator / gcd_value) != 0);

				return fraction(numerator / gcd_value,
								denominator / gcd_value);
			}
Exemple #14
0
    bool convert(const String &input, Time &outResult, bool ignoreWhiteSpace)
    {
      outResult = Time();

      String temp = input;
      if (ignoreWhiteSpace)
        temp.trim();

      String more;

      std::size_t posMore = temp.find('.');

      if (std::string::npos != posMore) {
        more = temp.substr(posMore+1);
        temp.erase(posMore);
      }

      if (std::string::npos != temp.find(':')) {
        std::tm ttm {};
        const char *parsed = strptime(temp.c_str(), "%Y-%m-%d %H:%M:%S", &ttm);
        if (NULL == parsed) return false;

        time_t ttime_t = mktime(&ttm);

        outResult = std::chrono::system_clock::from_time_t(ttime_t);
      } else {
        try {
          zsLib::Seconds::rep seconds = Numeric<zsLib::Seconds::rep>(temp);
          outResult = zsLib::timeSinceEpoch(zsLib::Seconds(seconds));
        } catch(Numeric<zsLib::Seconds::rep>::ValueOutOfRange &) {
          return false;
        }
      }

      if (more.hasData()) {
        String fractionStr("0.");
        fractionStr += more;

        double x {};

        try {
          x = std::stod(fractionStr);
        } catch(...) {
          return false;
        }

        x = x * 1000000;

        std::chrono::microseconds fraction(static_cast<unsigned long>(round(x)));

        outResult += fraction;
      }

      return true;
    }
Exemple #15
0
			fraction get_invert() const
			{
				if (numerator == 0)
					throw std::runtime_error("zero divide exception.");

				value_type sign_factor =
					numerator < 0 ? -1 : 1;

				assert((denominator * sign_factor) != 0);

				return fraction(denominator * sign_factor,
								numerator * sign_factor);
			}
Exemple #16
0
static WORLDBLT *xscaleblt(WORLDBLT *worldblt, double m11)
{
	/* perform scale operation
	 *	| m11   0   0 |
	 *	|   0   1   0 |
	 *	|   0   0   1 |
	 */

	int m11_numer, m11_denom;

	fraction(m11, &m11_numer, &m11_denom);

	LOGSTR((LF_LOG, "xscaleblt: %p, m11 = %f = (%d / %d)\n",
		worldblt, m11, m11_numer, m11_denom));

	if (!worldblt)
		return ((WORLDBLT *) 0);

	if (m11_numer == m11_denom)
		return (worldblt);

	if (m11_numer == -m11_denom)
		return (xmirrorblt(worldblt));

	if (m11_numer < 0)
	{
		worldblt = xmirrorblt(worldblt);
		m11 = -m11;
		m11_numer = -m11_numer;
		LOGSTR((LF_LOG, "xscaleblt: %p, m11 = %f = (%d / %d)\n",
			worldblt, m11, m11_numer, m11_denom));
	}

	if (m11_denom < 0)
	{
		worldblt = xmirrorblt(worldblt);
		m11 = -m11;
		m11_denom = -m11_denom;
		LOGSTR((LF_LOG, "xscaleblt: %p, m11 = %f = (%d / %d)\n",
			worldblt, m11, m11_numer, m11_denom));
	}




	return (worldblt);

}
Exemple #17
0
static WORLDBLT *yscaleblt(WORLDBLT *worldblt, double m22)
{
	/* perform scale operation
	 *	|   1   0   0 |
	 *	|   0 m22   0 |
	 *	|   0   0   1 |
	 */

	int m22_numer, m22_denom;

	fraction(m22, &m22_numer, &m22_denom);

	LOGSTR((LF_LOG, "yscaleblt: %p, m22 = %f = (%d / %d)\n",
		worldblt, m22, m22_numer, m22_denom));

	if (!worldblt)
		return ((WORLDBLT *) 0);

	if (m22_numer == m22_denom)
		return (worldblt);

	if (m22_numer == -m22_denom)
		return (ymirrorblt(worldblt));

	if (m22_numer < 0)
	{
		worldblt = ymirrorblt(worldblt);
		m22 = -m22;
		m22_numer = -m22_numer;
		LOGSTR((LF_LOG, "yscaleblt: %p, m22 = %f = (%d / %d)\n",
			worldblt, m22, m22_numer, m22_denom));
	}

	if (m22_denom < 0)
	{
		worldblt = ymirrorblt(worldblt);
		m22 = -m22;
		m22_denom = -m22_denom;
		LOGSTR((LF_LOG, "yscaleblt: %p, m22 = %f = (%d / %d)\n",
			worldblt, m22, m22_numer, m22_denom));
	}



	return (worldblt);

}
Exemple #18
0
EPtr FunctionNumeric::apply_evaled(EPtr arguments, State &state) {
    Number *value = Element::as_number(Pair::car(arguments));
    if (! value) return state.error("first argument must be numeric");
    Fractional v = value->value();
    BigInt fractions(5);
    Element *next = Pair::cdr(arguments);
    if (next) {
        Number *digits = Element::as_number(Pair::car(next));
        if (! digits) return state.error("second argument must be numeric");
        if (Pair::cdr(next)) return state.error("too many arguments");
        if (digits->value().denominator() != BigInt(1)) return state.error("digits must be integer");
        fractions = digits->value().numerator();
    }
    Fractional rounding(1, 2);
    Fractional ten(10);
    Fractional one(1);
    Fractional zero(0);
    
    for (Fractional i = fractions; zero < i; i = i - one) {
        rounding = rounding / ten;
    }
    v = v + rounding;
    
    std::ostringstream buffer;
    Fractional fraction(0);
    if (v.denominator() > BigInt(1)) {
        BigInt rest = v.numerator() % v.denominator();
        Fractional full = v - Fractional(rest, v.denominator(), v.isNegative());
        buffer << full;
        fraction = v - full;
    } else {
        buffer << v;
        fraction = Fractional(0);
    }
    buffer << ".";
    
    BigInt bi_one(1);
    for (BigInt cur(0); cur < fractions; cur = cur + bi_one) {
        fraction = fraction * ten;
        BigInt rest = fraction.numerator() % fraction.denominator();
        Fractional full = fraction - Fractional(rest, fraction.denominator(), fraction.isNegative());
        buffer << full;
        fraction = fraction - full;
    }
    
    return state.creator()->new_string(buffer.str());
}
Exemple #19
0
void StereoDelay::tick( sampleFrame frame )
{
	m_buffer[m_index][0] = frame[0];
	m_buffer[m_index][1] = frame[1];

	int readIndex = m_index - ( int )m_length - 1;
	if( readIndex < 0 )
	{
		readIndex += m_maxLength;
	}
	float fract = 1.0f -  fraction( m_length );
	frame[0] = linearInterpolate( m_buffer[readIndex][0] ,
			m_buffer[( readIndex+1) % m_maxLength][0], fract );
	frame[1] = linearInterpolate( m_buffer[readIndex][1] ,
			m_buffer[( readIndex+1) % m_maxLength][1], fract );

	m_buffer[m_index][0] += frame[0] * m_feedback;
	m_buffer[m_index][1] += frame[1] * m_feedback;

	m_index = ( m_index + 1) % m_maxLength;
}
Exemple #20
0
void MonoDelay::tick( sample_t* sample )
{
	m_buffer[m_index] = *sample;
	int readIndex = m_index - ( int )m_length - 1;
	if(readIndex < 0)
	{
		readIndex += m_maxLength;
	}
	float fract = 1.0f - fraction( m_length );
	if(readIndex != m_maxLength-1 )
	{
		*sample = linearInterpolate(m_buffer[readIndex] ,
									m_buffer[readIndex+1], fract );
	} else
	{
		*sample = linearInterpolate(m_buffer[readIndex] ,
									m_buffer[0], fract );
	}
	m_buffer[m_index] += *sample * m_feedback;
	m_index = ( m_index +1 ) % m_maxLength;
}
Exemple #21
0
sample_t bSynth::nextStringSample()
{
	float sample_step = 
		static_cast<float>( sample_length / ( sample_rate / nph->frequency() ) );

	
	// check overflow
	while (sample_realindex >= sample_length) {
		sample_realindex -= sample_length;
	}

	sample_t sample;

	if (interpolation) {

		// find position in shape 
		int a = static_cast<int>(sample_realindex);	
		int b;
		if (a < (sample_length-1)) {
			b = static_cast<int>(sample_realindex+1);
		} else {
			b = 0;
		}
		
		// Nachkommaanteil
		const float frac = fraction( sample_realindex );
		
		sample = linearInterpolate( sample_shape[a], sample_shape[b], frac );

	} else {
		// No interpolation
		sample_index = static_cast<int>(sample_realindex);	
		sample = sample_shape[sample_index];
	}
	
	// progress in shape
	sample_realindex += sample_step;

	return sample;
}	
  price::operator std::string()const
  {
     uint64_t integer = ratio.high_bits();
     fc::uint128 one(1,0);

     fc::uint128 fraction(0,ratio.low_bits());
     fraction *= BASE10_PRECISION;
     fraction /= one;
     fraction += BASE10_PRECISION;
     if( fraction.to_uint64()  % 10 >= 5 )
     {
        fraction += 10 - (fraction.to_uint64()  % 10);
        integer += ((fraction / BASE10_PRECISION) - 1).to_uint64();
     }
     std::string s = fc::to_string(integer);
     s += ".";
     std::string frac(fraction);
     s += frac.substr(1,frac.size()-2);
     s += " " + fc::to_string(quote_unit);
     s += "/" + fc::to_string(base_unit); 
     return s;
  }
Exemple #23
0
int main(void){
    int i,j,n;
    long long int a,b,c,d,tmp;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
        for(j=1;j<=i;j++)
            scanf("%lld%lld",&pin[i][j].l,&pin[i][j].r);
    ans[0][1].l=1;
    ans[0][1].r=1;
    for(i=1;i<=n;i++)
        for(j=1;j<=i+1;j++){
            if(j-1>0){
                a = ans[i-1][j-1].l*pin[i][j-1].r;
                b = ans[i-1][j-1].r*(pin[i][j-1].l+pin[i][j-1].r);
                tmp = gcd(a,b);
                a /= tmp;
                b /= tmp;
            }
            else{
                a=0;
                b=1;
            }
            if(j<=i){
                c = ans[i-1][j].l*pin[i][j].l;
                d = ans[i-1][j].r*(pin[i][j].l+pin[i][j].r);
                tmp = gcd(c,d);
                c /= tmp;
                d /= tmp;
            }
            else{
                c=0;
                d=1;
            }
            fraction(a,b,c,d,i,j);
        }
    for(i=1;i<=n+1;i++)
        printf("%lld/%lld\n",ans[n][i].l,ans[n][i].r);
    return 0;
}
Exemple #24
0
int main(){
    typedef CGAL::Fraction_traits<CGAL::Gmpq> FT;
    typedef FT::Numerator_type Numerator_type;
    typedef FT::Denominator_type Denominator_type;

    CGAL_static_assertion((boost::is_same<Numerator_type,CGAL::Gmpz>::value));
    CGAL_static_assertion((boost::is_same<Denominator_type,CGAL::Gmpz>::value));

    Numerator_type numerator;
    Denominator_type denominator;
    CGAL::Gmpq fraction(4,5);
    FT::Decompose()(fraction,numerator,denominator);

    CGAL::set_pretty_mode(std::cout);
    std::cout << "decompose fraction: "<< std::endl;
    std::cout << "fraction   : " << fraction << std::endl;
    std::cout << "numerator  : " << numerator<< std::endl;
    std::cout << "denominator: " << denominator << std::endl;

    std::cout << "re-compose fraction: "<< std::endl;
    fraction = FT::Compose()(numerator,denominator);
    std::cout << "fraction   : " << fraction << std::endl;
}
Exemple #25
0
int main() {
    const size_t iterations = 1000;

    Measure measure;

    size_t exceeds = 0;
    Fraction<mpz_class> fraction(0,1);
    for(size_t i=0;i<iterations;i++) {
        auto f = fraction + 1;
        if(digit_number_diff(f.p(),f.q()) > 0) exceeds += 1;
        //std::cout << i << " -> " << f << std::endl;
        fraction = next_fraction(fraction);
    }

    auto passed = measure.passed();
    if(!util::test_mode()) {
        std::cout << "Search took " << passed << " ms" << std::endl;
        std::cout << "Fractions containing a numerator with more digits than denominator: " << exceeds << std::endl;
    } else {
        std::cout << exceeds << std::endl;
    }

    return 0;
}
Exemple #26
0
fraction operator/(const fraction&a, const fraction&b)
{
	return fraction(a.numerator * b.denominator, a.denominator * b.numerator);
}
static char* toStringWithRadix(RadixBuffer& buffer, double number, unsigned radix)
{
    ASSERT(std::isfinite(number));
    ASSERT(radix >= 2 && radix <= 36);

    // Position the decimal point at the center of the string, set
    // the startOfResultString pointer to point at the decimal point.
    char* decimalPoint = buffer + sizeof(buffer) / 2;
    char* startOfResultString = decimalPoint;

    // Extract the sign.
    bool isNegative = number < 0;
    if (std::signbit(number))
        number = -number;
    double integerPart = floor(number);

    // We use this to test for odd values in odd radix bases.
    // Where the base is even, (e.g. 10), to determine whether a value is even we need only
    // consider the least significant digit. For example, 124 in base 10 is even, because '4'
    // is even. if the radix is odd, then the radix raised to an integer power is also odd.
    // E.g. in base 5, 124 represents (1 * 125 + 2 * 25 + 4 * 5). Since each digit in the value
    // is multiplied by an odd number, the result is even if the sum of all digits is even.
    //
    // For the integer portion of the result, we only need test whether the integer value is
    // even or odd. For each digit of the fraction added, we should invert our idea of whether
    // the number is odd if the new digit is odd.
    //
    // Also initialize digit to this value; for even radix values we only need track whether
    // the last individual digit was odd.
    bool integerPartIsOdd = integerPart <= static_cast<double>(0x1FFFFFFFFFFFFFull) && static_cast<int64_t>(integerPart) & 1;
    ASSERT(integerPartIsOdd == static_cast<bool>(fmod(integerPart, 2)));
    bool isOddInOddRadix = integerPartIsOdd;
    uint32_t digit = integerPartIsOdd;

    // Check if the value has a fractional part to convert.
    double fractionPart = number - integerPart;
    if (fractionPart) {
        // Write the decimal point now.
        *decimalPoint = '.';

        // Higher precision representation of the fractional part.
        Uint16WithFraction fraction(fractionPart);

        bool needsRoundingUp = false;
        char* endOfResultString = decimalPoint + 1;

        // Calculate the delta from the current number to the next & previous possible IEEE numbers.
        double nextNumber = nextafter(number, std::numeric_limits<double>::infinity());
        double lastNumber = nextafter(number, -std::numeric_limits<double>::infinity());
        ASSERT(std::isfinite(nextNumber) && !std::signbit(nextNumber));
        ASSERT(std::isfinite(lastNumber) && !std::signbit(lastNumber));
        double deltaNextDouble = nextNumber - number;
        double deltaLastDouble = number - lastNumber;
        ASSERT(std::isfinite(deltaNextDouble) && !std::signbit(deltaNextDouble));
        ASSERT(std::isfinite(deltaLastDouble) && !std::signbit(deltaLastDouble));

        // We track the delta from the current value to the next, to track how many digits of the
        // fraction we need to write. For example, if the value we are converting is precisely
        // 1.2345, so far we have written the digits "1.23" to a string leaving a remainder of
        // 0.45, and we want to determine whether we can round off, or whether we need to keep
        // appending digits ('4'). We can stop adding digits provided that then next possible
        // lower IEEE value is further from 1.23 than the remainder we'd be rounding off (0.45),
        // which is to say, less than 1.2255. Put another way, the delta between the prior
        // possible value and this number must be more than 2x the remainder we'd be rounding off
        // (or more simply half the delta between numbers must be greater than the remainder).
        //
        // Similarly we need track the delta to the next possible value, to dertermine whether
        // to round up. In almost all cases (other than at exponent boundaries) the deltas to
        // prior and subsequent values are identical, so we don't need track then separately.
        if (deltaNextDouble != deltaLastDouble) {
            // Since the deltas are different track them separately. Pre-multiply by 0.5.
            Uint16WithFraction halfDeltaNext(deltaNextDouble, 1);
            Uint16WithFraction halfDeltaLast(deltaLastDouble, 1);

            while (true) {
                // examine the remainder to determine whether we should be considering rounding
                // up or down. If remainder is precisely 0.5 rounding is to even.
                int dComparePoint5 = fraction.comparePoint5();
                if (dComparePoint5 > 0 || (!dComparePoint5 && (radix & 1 ? isOddInOddRadix : digit & 1))) {
                    // Check for rounding up; are we closer to the value we'd round off to than
                    // the next IEEE value would be?
                    if (fraction.sumGreaterThanOne(halfDeltaNext)) {
                        needsRoundingUp = true;
                        break;
                    }
                } else {
                    // Check for rounding down; are we closer to the value we'd round off to than
                    // the prior IEEE value would be?
                    if (fraction < halfDeltaLast)
                        break;
                }

                ASSERT(endOfResultString < (buffer + sizeof(buffer) - 1));
                // Write a digit to the string.
                fraction *= radix;
                digit = fraction.floorAndSubtract();
                *endOfResultString++ = radixDigits[digit];
                // Keep track whether the portion written is currently even, if the radix is odd.
                if (digit & 1)
                    isOddInOddRadix = !isOddInOddRadix;

                // Shift the fractions by radix.
                halfDeltaNext *= radix;
                halfDeltaLast *= radix;
            }
        } else {
            // This code is identical to that above, except since deltaNextDouble != deltaLastDouble
            // we don't need to track these two values separately.
            Uint16WithFraction halfDelta(deltaNextDouble, 1);

            while (true) {
                int dComparePoint5 = fraction.comparePoint5();
                if (dComparePoint5 > 0 || (!dComparePoint5 && (radix & 1 ? isOddInOddRadix : digit & 1))) {
                    if (fraction.sumGreaterThanOne(halfDelta)) {
                        needsRoundingUp = true;
                        break;
                    }
                } else if (fraction < halfDelta)
                    break;

                ASSERT(endOfResultString < (buffer + sizeof(buffer) - 1));
                fraction *= radix;
                digit = fraction.floorAndSubtract();
                if (digit & 1)
                    isOddInOddRadix = !isOddInOddRadix;
                *endOfResultString++ = radixDigits[digit];

                halfDelta *= radix;
            }
        }

        // Check if the fraction needs rounding off (flag set in the loop writing digits, above).
        if (needsRoundingUp) {
            // Whilst the last digit is the maximum in the current radix, remove it.
            // e.g. rounding up the last digit in "12.3999" is the same as rounding up the
            // last digit in "12.3" - both round up to "12.4".
            while (endOfResultString[-1] == radixDigits[radix - 1])
                --endOfResultString;

            // Radix digits are sequential in ascii/unicode, except for '9' and 'a'.
            // E.g. the first 'if' case handles rounding 67.89 to 67.8a in base 16.
            // The 'else if' case handles rounding of all other digits.
            if (endOfResultString[-1] == '9')
                endOfResultString[-1] = 'a';
            else if (endOfResultString[-1] != '.')
                ++endOfResultString[-1];
            else {
                // One other possibility - there may be no digits to round up in the fraction
                // (or all may be been rounded off already), in which case we may need to
                // round into the integer portion of the number. Remove the decimal point.
                --endOfResultString;
                // In order to get here there must have been a non-zero fraction, in which case
                // there must be at least one bit of the value's mantissa not in use in the
                // integer part of the number. As such, adding to the integer part should not
                // be able to lose precision.
                ASSERT((integerPart + 1) - integerPart == 1);
                ++integerPart;
            }
        } else {
            // We only need to check for trailing zeros if the value does not get rounded up.
            while (endOfResultString[-1] == '0')
                --endOfResultString;
        }

        *endOfResultString = '\0';
        ASSERT(endOfResultString < buffer + sizeof(buffer));
    } else
        *decimalPoint = '\0';

    BigInteger units(integerPart);

    // Always loop at least once, to emit at least '0'.
    do {
        ASSERT(buffer < startOfResultString);

        // Read a single digit and write it to the front of the string.
        // Divide by radix to remove one digit from the value.
        digit = units.divide(radix);
        *--startOfResultString = radixDigits[digit];
    } while (!!units);

    // If the number is negative, prepend '-'.
    if (isNegative)
        *--startOfResultString = '-';
    ASSERT(buffer <= startOfResultString);

    return startOfResultString;
}
// this code for ROC is taken (and adjusted a bit) from PERF software:
//R. Caruana, The PERF Performance Evaluation Code,
// http://www.cs.cornell.edu/~caruana/perf
double roc(doublev& preds, doublev& tars)
{
    int itemN = (int)preds.size();

    ddpairv data(itemN);
    bool onlyOnes = true;
    bool onlyZeros = true;
    for(int i = 0; i < itemN; i++)
    {
        data[i].first = preds[i];
        data[i].second = tars[i];
        if((tars[i] < 0) || (tars[i] > 1))
            throw ROC_ERR;
        if(tars[i] != 0)
            onlyZeros = false;
        if(tars[i] != 1)
            onlyOnes = false;
    }
    if(onlyZeros || onlyOnes)
        throw ROC_FLAT_ERR;

    sort(data.begin(), data.end());

    /* get the fractional weights. If there are ties we count the number
    of cases tied and how many positives there are, and we assign
    each case to be #poz/#cases positive and the rest negative */

    doublev fraction(itemN);
    int item = 0;
    while(item < itemN)
    {
        int begin = item;
        double posV = 0;
        for(; (item < itemN) && (data[item].first == data[begin].first); item++)
            posV += data[item].second;

        double curFrac = posV / (item - begin);
        for(int i = begin; i < item; i++)
            fraction[i] = curFrac;
    }

    double tt = 0;
    double tf = 0;
    double ft = 0;
    double ff = 0;

    //initialize tf and ff with ground truth
    for(int i = 0; i < itemN; i++)
    {
        tf += data[i].second;
        ff += 1 - data[i].second;
    }

    double roc_area = 0.0;
    double tpf_prev = 0;
    double fpf_prev = 0;

    for(item = itemN - 1; item > -1; item--)
    {
        tt += fraction[item];
        tf -= fraction[item];
        ft += 1 - fraction[item];
        ff -= 1 - fraction[item];
        double tpf  = tt / (tt + tf);
        double fpf  = 1.0 - ff / (ft + ff);
        roc_area += 0.5 * (tpf + tpf_prev) * (fpf - fpf_prev);
        tpf_prev = tpf;
        fpf_prev = fpf;
    }

    return roc_area;
}
Exemple #29
0
fraction operator/(const fraction &x, const fraction &y)
{
    int newNum = x.num *y.denom ,
        newDenom = x.denom * y.num;
    return fraction(newNum, newDenom);
}
Exemple #30
0
fraction fraction::divide(const fraction &na, const fraction &nb) {
	return(fraction(na.numerator * nb.denominator, na.denominator * nb.numerator));
}