Class: Calc::Q

Inherits:
Numeric show all
Includes:
Comparable
Defined in:
ext/calc/q.c,
lib/calc/q.rb,
ext/calc/q.c

Overview

Calc rational number (fraction).

A rational number consists of an arbitrarily large numerator and denominator. The numerator and denominator are always in lowest terms, and the sign of the number is contained in the numerator.

Wraps the libcalc C type NUMBER*.

Constant Summary collapse

NEGONE =
new(-1)
ZERO =
new(0)
ONE =
new(1)
TWO =
new(2)

Instance Method Summary collapse

Methods inherited from Numeric

#%, #+@, #<<, #>>, #abs2, #ceil, #cmp, #coerce, #comb, #fdiv, #finite?, #floor, #ilog, #ilog10, #ilog2, #infinite?, #isint, #ln, #log, #log2, #mmin, #nonzero?, #polar, #quo, #rectangular, #root, #scale, #sgn, #sqrt, #to_int

Constructor Details

#initialize(*args) ⇒ Calc::Q

Creates a new rational number.

Arguments are either a numerator/denominator pair, or a single numerator. With a single parameter, a denominator of 1 is implied. Valid types are:

  • Integer

  • Rational

  • Calc::Q

  • String

  • Float

Strings can be in rational, floating point, exponential, hex or octal, eg:

Calc::Q("3/10")   #=> Calc::Q(0.3)
Calc::Q("0.5")    #=> Calc::Q(0.5)
Calc::Q("1e10")   #=> Calc::Q(10000000000)
Calc::Q("1e-10")  #=> Calc::Q(0.0000000001)
Calc::Q("0x2a")   #=> Calc::Q(42)
Calc::Q("052")    #=> Calc::Q(42)

Note that a Float cannot precisely equal many values; it will be converted the the closest rational number which may not be what you expect, eg:

Calc::Q(0.3)  #=> Calc::Q(~0.29999999999999998890)

for this reason, it is best to avoid Floats. Libcalc’s string parsing will work better:

Calc::Q("0.3")  #=> Calc::Q(0.3)

Parameters:

Raises:

  • (ZeroDivisionError)

    if denominator of new number is zero



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'ext/calc/q.c', line 93

static VALUE
cq_initialize(int argc, VALUE * argv, VALUE self)
{
    NUMBER *qself, *qnum, *qden;
    VALUE num, den;
    setup_math_error();

    if (rb_scan_args(argc, argv, "11", &num, &den) == 1) {
        /* single param */
        qself = value_to_number(num, 1);
    }
    else {
        /* 2 params. divide first by second. */
        qden = value_to_number(den, 1);
        if (qiszero(qden)) {
            qfree(qden);
            rb_raise(rb_eZeroDivError, "division by zero");
        }
        qnum = value_to_number(num, 1);
        qself = qqdiv(qnum, qden);
        qfree(qden);
        qfree(qnum);
    }
    DATA_PTR(self) = qself;

    return self;
}

Instance Method Details

#&(y) ⇒ Calc::Q

Bitwise AND

Examples:

Calc::Q(18) & 20 #=> Calc::Q(16)

Parameters:

  • y (Integer)

Returns:



348
349
350
351
352
# File 'ext/calc/q.c', line 348

static VALUE
cq_and(VALUE x, VALUE y)
{
    return numeric_op(x, y, &qand, NULL, id_and);
}

#*(y) ⇒ Calc::Q

Performs multiplication.

@example:

Calc::Q(2) * 3 #=> Calc::Q(6)

Parameters:

Returns:



361
362
363
364
365
# File 'ext/calc/q.c', line 361

static VALUE
cq_multiply(VALUE x, VALUE y)
{
    return numeric_op(x, y, &qmul, &qmuli, id_multiply);
}

#**(other) ⇒ Object



8
9
10
# File 'lib/calc/q.rb', line 8

def **(other)
  power(other)
end

#+(y) ⇒ Calc::Q

Performs addition.

Examples:

Calc::Q(1) + 2 #=> Calc::Q(3)

Parameters:

Returns:



374
375
376
377
378
379
# File 'ext/calc/q.c', line 374

static VALUE
cq_add(VALUE x, VALUE y)
{
    /* fourth arg was &qaddi, but this segfaults with ruby 2.1.x */
    return numeric_op(x, y, &qqadd, NULL, id_add);
}

#-(y) ⇒ Calc::Q

Performs subtraction.

@example:

Calc::Q(1) - 2 #=> Calc::Q(-1)

Parameters:

Returns:



388
389
390
391
392
# File 'ext/calc/q.c', line 388

static VALUE
cq_subtract(VALUE x, VALUE y)
{
    return numeric_op(x, y, &qsub, NULL, id_subtract);
}

#-@Calc::Q

Unary minus. Returns the receiver’s value, negated.

Examples:

-Calc::Q(1) #=> Calc::Q(-1)

Returns:



400
401
402
403
404
405
# File 'ext/calc/q.c', line 400

static VALUE
cq_uminus(VALUE self)
{
    setup_math_error();
    return wrap_number(qsub(&_qzero_, DATA_PTR(self)));
}

#/(y) ⇒ Calc::Q

Performs division.

@example:

Calc::Q(2) / 4 #=> Calc::Q(0.5)

Parameters:

Returns:

Raises:



415
416
417
418
419
# File 'ext/calc/q.c', line 415

static VALUE
cq_divide(VALUE x, VALUE y)
{
    return numeric_op(x, y, &qqdiv, &qdivi, id_divide);
}

#<=>(other) ⇒ Integer?

Comparison - Returns -1, 0, +1 or nil depending on whether ‘y` is less than, equal to, or greater than `x`.

This is used by the ‘Comparable` module to implement `==`, `!=`, `<`, `<=`, `>` and `>=`.

nil is returned if the two values are incomparable.

@example:

Calc::Q(5) <=> 4     #=> 1
Calc::Q(5) <=> 5.1   #=> -1
Calc::Q(5) <=> 5     #=> 0
Calc::Q(5) <=> "cat" #=> nil

Parameters:

Returns:

  • (Integer, nil)


437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'ext/calc/q.c', line 437

static VALUE
cq_spaceship(VALUE self, VALUE other)
{
    VALUE ary;
    NUMBER *qself, *qother;
    int result;
    setup_math_error();

    qself = DATA_PTR(self);
    /* qreli returns incorrect results if self > 0 and other == 0
       if (FIXNUM_P(other)) {
       result = qreli(qself, NUM2LONG(other));
       }
     */
    if (CALC_Q_P(other)) {
        result = qrel(qself, DATA_PTR(other));
    }
    else if (FIXNUM_P(other) || RB_TYPE_P(other, T_BIGNUM) || RB_TYPE_P(other, T_FLOAT)
             || RB_TYPE_P(other, T_RATIONAL)) {
        qother = value_to_number(other, 0);
        result = qrel(qself, qother);
        qfree(qother);
    }
    else if (rb_respond_to(other, id_coerce)) {
        if (RB_TYPE_P(other, T_COMPLEX)) {
            other = rb_funcall(cC, id_new, 1, other);
        }
        ary = rb_funcall(other, id_coerce, 1, self);
        if (!RB_TYPE_P(ary, T_ARRAY) || RARRAY_LEN(ary) != 2) {
            rb_raise(rb_eTypeError, "coerce must return [x, y]");
        }
        return rb_funcall(RARRAY_AREF(ary, 0), id_spaceship, 1, RARRAY_AREF(ary, 1));
    }
    else {
        return Qnil;
    }

    return INT2FIX(result);
}

#^(y) ⇒ Calc::Q

Bitwise exclusive or (xor)

Note that for ruby compatibility, ^ is an xor operator, unlike in calc where it is a power operator.

Examples:

Calc::Q(5).xor(3) #=> Calc::Q(6)

Returns:



486
487
488
489
490
# File 'ext/calc/q.c', line 486

static VALUE
cq_xor(VALUE x, VALUE y)
{
    return numeric_op(x, y, &qxor, NULL, id_xor);
}

#absCalc::Q Also known as: magnitude

Absolute value

Examples:

Calc::Q(1).abs  #=> Calc::Q(1)
Calc::Q(-1).abs #=> Calc::Q(1)

Returns:



527
528
529
530
531
532
# File 'ext/calc/q.c', line 527

static VALUE
cq_abs(VALUE self)
{
    setup_math_error();
    return wrap_number(qqabs(DATA_PTR(self)));
}

#acos(*args) ⇒ Calc::Q, Calc::C

Inverse trigonometric cosine

Examples:

Calc::Q(0.5).acos #=> Calc::Q(1.04719755119659774615)
Calc::Q(2.0).acos #=> Calc::C(1.31695789692481670863i)

Parameters:

Returns:



542
543
544
545
546
# File 'ext/calc/q.c', line 542

static VALUE
cq_acos(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qacos, &c_acos);
}

#acosh(*args) ⇒ Calc::Q, Calc::C

Inverse hyperbolic cosine

Examples:

Calc::Q(2).acosh #=> Calc::Q(1.31695789692481670862)
Calc::Q(0).acosh #=> Calc::C(1.57079632679489661923i)

Parameters:

Returns:



556
557
558
559
560
# File 'ext/calc/q.c', line 556

static VALUE
cq_acosh(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qacosh, &c_acosh);
}

#acot(*args) ⇒ Calc::Q

Inverse trigonometric cotangent

Examples:

Calc::Q(2).acot #=> Calc::Q(0.46364760900080611621)

Parameters:

Returns:



569
570
571
572
573
# File 'ext/calc/q.c', line 569

static VALUE
cq_acot(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qacot, NULL);
}

#acoth(*args) ⇒ Calc::Q, Calc::C

Inverse hyperbolic cotangent

Examples:

Calc::Q(2).acoth   #=> Calc::Q(0.5493061443340548457)
Calc::Q(0.5).acoth #=> Calc::C(0.5493061443340548457+1.57079632679489661923i)

Parameters:

Returns:



583
584
585
586
587
# File 'ext/calc/q.c', line 583

static VALUE
cq_acoth(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qacoth, &c_acoth);
}

#acsc(*args) ⇒ Calc::Q, Calc::C

Inverse trigonometric cosecant

Examples:

Calc::Q(2).acsc   #=> Calc::Q(0.52359877559829887308)
Calc::Q(0.5).acsc #=> Calc::C(1.57079632679489661923-1.31695789692481670863i)

Parameters:

Returns:



597
598
599
600
601
# File 'ext/calc/q.c', line 597

static VALUE
cq_acsc(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qacsc, &c_acsc);
}

#acsch(*args) ⇒ Calc::Q

Inverse hyperbolic cosecant

Examples:

Calc::Q(2).acsch #=> Calc::Q(0.4812118250596034475)

Parameters:

Returns:

Raises:



611
612
613
614
615
# File 'ext/calc/q.c', line 611

static VALUE
cq_acsch(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qacsch, &c_acsch);
}

#agd(*args) ⇒ Calc::Q, Calc::C

Inverse gudermannian function

Examples:

Calc::Q(1).agd #=> Calc::Q(1.22619117088351707081)
Calc::Q(2).agd #=> Calc::C(1.5234524435626735209-3.14159265358979323846i)

Parameters:

  • eps (Calc::Q)

    (optional) calculation accuracy

Returns:



19
20
21
22
# File 'lib/calc/q.rb', line 19

def agd(*args)
  r = Calc::C(self).agd(*args)
  r.real? ? r.re : r
end

#appr(*args) ⇒ Object

Approximate numbers by multiples of a specified number

Returns the approximate value of self as specified by an error (defaults to Calc.config(:epsilon)) and rounding mode (defaults to Calc.config(:appr)).

Type “help appr” in calc for a description of the rounding modes.

Examples:

Calc::Q("5.44").appr("0.1",0) #=> Calc::Q(5.4)

Parameters:

  • y (Numeric, Calc::Q)

    (optional) error

  • z (Interger)

    (optional) rounding mode



629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
# File 'ext/calc/q.c', line 629

static VALUE
cq_appr(int argc, VALUE * argv, VALUE self)
{
    VALUE result, epsilon, rounding;
    NUMBER *qepsilon, *qrounding;
    long R = 0;
    int n;
    setup_math_error();

    n = rb_scan_args(argc, argv, "02", &epsilon, &rounding);
    if (n == 2) {
        if (FIXNUM_P(rounding)) {
            R = FIX2LONG(rounding);
        }
        else {
            qrounding = value_to_number(rounding, 1);
            if (qisfrac(qrounding)) {
                rb_raise(e_MathError, "fractional rounding for appr");
            }
            R = qtoi(DATA_PTR(qrounding));
            qfree(qrounding);
        }
    }
    else {
        R = conf->appr;
    }
    if (n >= 1) {
        qepsilon = value_to_number(epsilon, 1);
    }
    else {
        qepsilon = NULL;
    }
    result = wrap_number(qmappr(DATA_PTR(self), qepsilon ? qepsilon : conf->epsilon, R));
    if (qepsilon) {
        qfree(qepsilon);
    }
    return result;
}

#arg(*args) ⇒ Calc::Q Also known as: angle, phase

Returns the argument (the angle or phase) of a complex number in radians

This method is used by non-complex classes, it will be 0 for positive values, pi() otherwise.

Examples:

Calc::Q(-1).arg #=> Calc::Q(3.14159265358979323846)
Calc::Q(1).arg  #=> Calc::Q(0)

Parameters:

  • eps (Calc::Q)

    (optional) calculation accuracy

Returns:



34
35
36
37
38
39
40
# File 'lib/calc/q.rb', line 34

def arg(*args)
  if self < 0
    Calc.pi(*args)
  else
    ZERO
  end
end

#asec(*args) ⇒ Calc::Q, Calc::C

Inverse trigonometric secant

Examples:

Calc::Q(2).asec #=> Calc::Q(1.04719755119659774615)

Parameters:

Returns:



675
676
677
678
679
# File 'ext/calc/q.c', line 675

static VALUE
cq_asec(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qasec, &c_asec);
}

#asech(*args) ⇒ Calc::Q, Calc::C

Inverse hyperbolic secant

Examples:

Calc::Q(0.5).asech #=> Calc::Q(1.31695789692481670862)

Parameters:

Returns:

Raises:



689
690
691
692
693
# File 'ext/calc/q.c', line 689

static VALUE
cq_asech(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qasech, &c_asech);
}

#asin(*args) ⇒ Calc::Q, Calc::C

Inverse trigonometric sine

Examples:

Calc::Q(0.5).asin #=> Calc::Q(0.52359877559829887308)

Parameters:

Returns:



702
703
704
705
706
# File 'ext/calc/q.c', line 702

static VALUE
cq_asin(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qasin, &c_asin);
}

#asinh(*args) ⇒ Calc::Q

Inverse hyperbolic sine

Examples:

Calc::Q(2).asinh #=> Calc::Q(1.44363547517881034249)

Parameters:

Returns:



715
716
717
718
719
# File 'ext/calc/q.c', line 715

static VALUE
cq_asinh(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qasinh, NULL);
}

#atan(*args) ⇒ Calc::Q

Inverse trigonometric tangent

Examples:

Calc::Q(2).atan #=> Calc::Q(1.10714871779409050302)

Parameters:

Returns:



728
729
730
731
732
# File 'ext/calc/q.c', line 728

static VALUE
cq_atan(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qatan, NULL);
}

#atan2(*args) ⇒ Calc::Q

Angle to point (arctangent with 2 arguments)

To match normal calling conventions, ‘y.atan2(x)` is equivalent to `Math.atan2(y,x)`. To avoid confusion, the class method may be preferrable: `Calc::Q.atan2(y,x)`.

Examples:

Calc::Q(0).atan2(0)   #=> Calc::Q(0)
Calc::Q(17).atan2(52) #=> Calc::Q(0.31597027195298044266)

Parameters:

Returns:



746
747
748
749
750
# File 'ext/calc/q.c', line 746

static VALUE
cq_atan2(int argc, VALUE * argv, VALUE self)
{
    return trans_function2(argc, argv, self, &qatan2);
}

#atanh(*args) ⇒ Calc::Q, Calc::C

Inverse hyperbolic tangent

Examples:

Calc::Q(0.5).atanh #=> Calc::Q(0.87758256189037271612)

Parameters:

Returns:



759
760
761
762
763
# File 'ext/calc/q.c', line 759

static VALUE
cq_atanh(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qatanh, &c_atanh);
}

#bernoulliCalc::Q

Returns the bernoulli number with index self. Self must be an integer, and < 2^31 if even.

Examples:

Calc::Q(20).bernoulli.to_s(:frac) #=> "-174611/330"

Returns:

Raises:



773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
# File 'ext/calc/q.c', line 773

static VALUE
cq_bernoulli(VALUE self)
{
    NUMBER *qself, *qresult;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisfrac(qself)) {
        rb_raise(e_MathError, "Non-integer argument for bernoulli");
    }
    qresult = qbern(qself->num);
    if (!qresult) {
        rb_raise(e_MathError, "Bad argument for bern");
    }
    return wrap_number(qresult);
}

#bit(y) ⇒ Calc::Q Also known as: []

Returns 1 if binary bit y is set in self, otherwise 0.

Examples:

Calc::Q(9).bit(0) #=> Calc::Q(1)
Calc::Q(9).bit(1) #=> Calc::Q(0)

Parameters:

Returns:

See Also:



52
53
54
# File 'lib/calc/q.rb', line 52

def bit(y)
  bit?(y) ? ONE : ZERO
end

#bit?(y) ⇒ Boolean

Returns true if binary bit y is set in self, otherwise false.

Examples:

Calc::Q(9).bit?(0) #=> true
Calc::Q(9).bit?(1) #=> false

Parameters:

Returns:

  • (Boolean)

See Also:



799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
# File 'ext/calc/q.c', line 799

static VALUE
cq_bitp(VALUE self, VALUE y)
{
    /* this is an "opcode" in calc rather than a builtin ("help bit" is
     * wrong!).  this is based on calc's opcodes.c#o_bit() */
    NUMBER *qself, *qy;
    long index;
    int r;
    setup_math_error();

    qself = DATA_PTR(self);
    qy = value_to_number(y, 0);
    if (qisfrac(qy)) {
        qfree(qy);
        rb_raise(e_MathError, "Bad argument type for bit");     /* E_BIT1 */
    }
    if (zge31b(qy->num)) {
        qfree(qy);
        rb_raise(e_MathError, "Index too large for bit");       /* E_BIT2 */
    }
    index = qtoi(qy);
    qfree(qy);
    r = qisset(qself, index);
    return r ? Qtrue : Qfalse;
}

#bit_lengthCalc::Q

Returns the number of bits in the integer part of ‘self`

Note that this is compatible with ruby’s Integer#bit_length. Libcalc provides a similar function called ‘highbit` with different semantics.

This returns the bit position of the highest bit which is different to the sign bit. If there is no such bit (zero or -1), zero is returned.

Examples:

Calc::Q(0xff).bit_length #=> Calc::Q(8)

Returns:



68
69
70
# File 'lib/calc/q.rb', line 68

def bit_length
  (negative? ? -self : self + ONE).log2.ceil
end

#bround(*args) ⇒ Calc::Q

Round to a specified number of binary digits

Rounds self rounded to the specified number of significant binary digits. For the meanings of the rounding flags, see “help bround”.

Examples:

Calc::Q(7,32).bround(3)  #=> Calc::Q(0.25)

Parameters:

  • places (Integer)

    number of binary digits to round to (default 0)

  • rnd (Integer)

    rounding flags (default Calc.config(:round)

Returns:



836
837
838
839
840
# File 'ext/calc/q.c', line 836

static VALUE
cq_bround(int argc, VALUE * argv, VALUE self)
{
    return rounding_function(argc, argv, self, &qbround);
}

#btrunc(*args) ⇒ Calc::Q

Truncate to a number of binary places

Truncates to j binary places. If j is omitted, 0 places is assumed. Truncation of a non-integer prouces values nearer to zero.

Examples:

Calc.pi.btrunc    #=> Calc::Q(3)
Calc.pi.btrunc(5) #=> Calc::Q(3.125)

Parameters:

  • j (Integer)

Returns:



853
854
855
856
857
# File 'ext/calc/q.c', line 853

static VALUE
cq_btrunc(int argc, VALUE * argv, VALUE self)
{
    return trunc_function(argc, argv, self, &qbtrunc);
}

#catalanCalc::Q

Returns the Catalan number for index self. If self is negative, zero is returned.

Examples:

Calc::Q(2).catalan  #=> Calc::Q(2)
Calc::Q(5).catalan  #=> Calc::Q(42)
Calc::Q(20).catalan #=> Calc::Q(6564120420)

Returns:

Raises:



869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
# File 'ext/calc/q.c', line 869

static VALUE
cq_catalan(VALUE self)
{
    NUMBER *qself, *qresult;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisfrac(qself)) {
        rb_raise(e_MathError, "Non-integer value for catalan");
    }
    else if (zge31b(qself->num)) {
        rb_raise(e_MathError, "Value too large for catalan");
    }
    qresult = qcatalan(qself);
    if (!qresult) {
        rb_raise(e_MathError, "qcatalan() returned NULL");
    }
    return wrap_number(qresult);
}

#cfappr(*args) ⇒ Calc::Q

Approximation using continued fractions

If self is an integer or eps is zero, returns x.

If abs(eps) < 1, returns the smallest denominator number in one of the three intervals [self, self+abs(eps)], [self-abs(eps), self], [self-abs(eps)/2, self+abs(eps)/2].

If eps >= 1 and den(self) > n, returns the nearest above, below or approximation with denominatior less than or equal to n.

If den(self) <= eps, returns self.

When the result is not self, the rounding is controlled by the final parameter; see “help cfappr” for details.

Examples:

Calc.pi.cfappr(1).to_s(:frac)   #=> "3"
Calc.pi.cfappr(10).to_s(:frac)  #=> "25/8"
Calc.pi.cfappr(50).to_s(:frac)  #=> "157/50"
Calc.pi.cfappr(100).to_s(:frac) #=> "311/99"

Parameters:

  • eps (Numeric)

    epsilon or upper limit of denominator (default: Calc.config(“epsilon”))

  • rnd (Integer)

    rounding flags (default: Calc.config(“cfappr”))

Returns:



914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
# File 'ext/calc/q.c', line 914

static VALUE
cq_cfappr(int argc, VALUE * argv, VALUE self)
{
    VALUE eps, rnd, result;
    NUMBER *q;
    long n, R;
    setup_math_error();

    n = rb_scan_args(argc, argv, "02", &eps, &rnd);
    q = (n >= 1) ? value_to_number(eps, 1) : conf->epsilon;
    R = (n == 2) ? value_to_long(rnd) : conf->cfappr;
    result = wrap_number(qcfappr(DATA_PTR(self), q, R));
    if (n >= 1) {
        qfree(q);
    }
    return result;
}

#cfsim(*args) ⇒ Calc::Q

Simplify using continued fractions

If self is not an integer, returns either the nearest above or below number with denominator less than self.den.

Rounding is controlled by rnd (default: Calc.config(:cfsim)).

See “help cfsim” for details of rounding values.

Repeated calls to cfsim give a sequence of good approximations with decreasing denominators and correspondinlgy decreasing accuracy.

Examples:

x = Calc.pi; while (!x.int?) do; x = x.cfsim; puts x.to_s(:frac) if x.den < 1e6; end
1146408/364913
312689/99532
104348/33215
355/113
22/7
3

Parameters:

  • rnd (Integer)

    rounding flags (default: Calc.config(:cfsim))

Returns:



955
956
957
958
959
960
961
962
963
964
965
# File 'ext/calc/q.c', line 955

static VALUE
cq_cfsim(int argc, VALUE * argv, VALUE self)
{
    VALUE rnd;
    long n, R;
    setup_math_error();

    n = rb_scan_args(argc, argv, "01", &rnd);
    R = (n >= 1) ? value_to_long(rnd) : conf->cfsim;
    return wrap_number(qcfsim(DATA_PTR(self), R));
}

#charString

Returns a string containing the character corresponding to a value

Note that this is for compatibility with calc, normally in ruby you should just #chr

Examples:

Calc::Q(88).char #=> "X"

Returns:

  • (String)

Raises:



80
81
82
83
84
85
86
87
88
# File 'lib/calc/q.rb', line 80

def char
  raise MathError, "Non-integer for char" unless int?
  raise MathError, "Out of range for char" unless between?(0, 255)
  if zero?
    ""
  else
    to_i.chr
  end
end

#chr(*args) ⇒ String

Returns a string containing the character represented by ‘self` value according to encoding.

Unlike the calc version (‘char`), this allows numbers greater than 255 if an encoding is specified.

Examples:

Calc::Q(88).chr                   #=> "X"
Calc::Q(300).chr(Encoding::UTF_8) #=> Unicode I-breve

Parameters:

  • encoding (Encoding)

Returns:

  • (String)


101
102
103
# File 'lib/calc/q.rb', line 101

def chr(*args)
  to_i.chr(*args)
end

#clamp(min, max) ⇒ Object



108
109
110
# File 'lib/calc/q.rb', line 108

def clamp(min, max)
  super(Q.new(min), Q.new(max))
end

#conjCalc::Q Also known as: conjugate

Complex conjugate

As the conjugate of real x is x, this method returns self.

Examples:

Calc::Q(3).conj #=> 3

Returns:



120
121
122
# File 'lib/calc/q.rb', line 120

def conj
  self
end

#cos(*args) ⇒ Calc::Q

Cosine

Examples:

Calc::Q(1).cos #=> Calc::Q(0.5403023058681397174)

Parameters:

Returns:



974
975
976
977
978
# File 'ext/calc/q.c', line 974

static VALUE
cq_cos(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qcos, NULL);
}

#cosh(*args) ⇒ Calc::Q

Hyperbolic cosine

Examples:

Calc::Q(1).cosh #=> Calc::Q(1.54308063481524377848)

Parameters:

Returns:



987
988
989
990
991
# File 'ext/calc/q.c', line 987

static VALUE
cq_cosh(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qcosh, NULL);
}

#cot(*args) ⇒ Calc::Q

Trigonometric cotangent

Examples:

Calc::Q(1).cot #=> Calc::Q(0.64209261593433070301)

Parameters:

Returns:

Raises:



1001
1002
1003
1004
1005
# File 'ext/calc/q.c', line 1001

static VALUE
cq_cot(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qcot, NULL);
}

#coth(*args) ⇒ Calc::Q

Hyperbolic cotangent

Examples:

Calc::Q(1).coth #=> Calc::Q(1.31303528549933130364)

Parameters:

Returns:

Raises:



1015
1016
1017
1018
1019
# File 'ext/calc/q.c', line 1015

static VALUE
cq_coth(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qcoth, NULL);
}

#csc(*args) ⇒ Calc::Q

Trigonometric cosecant

Examples:

Calc::Q(1).csc #=> Calc::Q(1.18839510577812121626)

Parameters:

Returns:



1028
1029
1030
1031
1032
# File 'ext/calc/q.c', line 1028

static VALUE
cq_csc(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qcsc, NULL);
}

#csch(*args) ⇒ Calc::Q

Hyperbolic cosecant

Examples:

Calc::Q(1).csch #=> Calc::Q(0.85091812823932154513)

Parameters:

Returns:

Raises:



1042
1043
1044
1045
1046
# File 'ext/calc/q.c', line 1042

static VALUE
cq_csch(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qcsch, NULL);
}

#denCalc::Q Also known as: denominator

Returns the denominator. Always positive.

@example:

Calc::Q(1,3).den  #=> Calc::Q(3)
Calc::Q(-1,3).den #=> Calc::Q(3)

Returns:



1055
1056
1057
1058
1059
1060
# File 'ext/calc/q.c', line 1055

static VALUE
cq_den(VALUE self)
{
    setup_math_error();
    return wrap_number(qden(DATA_PTR(self)));
}

#digit(*args) ⇒ Calc::Q

Returns the digit at the specified position on decimal or any other base.

Examples:

Calc::Q("123456.789").digit(3)  #=> Calc::Q(3)
Calc::Q("123456.789").digit(-3) #=> Calc::Q(9)

Parameters:

  • n (Integer)

    index. negative indices are to the right of any decimal point

  • b (Integer)

    (optional) base >= 2 (default 10)

Returns:



1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# File 'ext/calc/q.c', line 1071

static VALUE
cq_digit(int argc, VALUE * argv, VALUE self)
{
    VALUE pos, base;
    NUMBER *qpos, *qbase, *qresult;
    long n;
    setup_math_error();

    n = rb_scan_args(argc, argv, "11", &pos, &base);
    qpos = value_to_number(pos, 1);
    if (qisfrac(qpos)) {
        qfree(qpos);
        rb_raise(e_MathError, "non-integer position for digit");
    }
    if (n >= 2) {
        qbase = value_to_number(base, 1);
        if (qisfrac(qbase)) {
            qfree(qpos);
            qfree(qbase);
            rb_raise(e_MathError, "non-integer base for digit");
        }
    }
    else {
        qbase = NULL;
    }
    qresult = qdigit(DATA_PTR(self), qpos->num, qbase ? qbase->num : _ten_);
    qfree(qpos);
    if (qbase)
        qfree(qbase);
    if (qresult == NULL) {
        rb_raise(e_MathError, "Invalid arguments for digit");
    }
    return wrap_number(qresult);
}

#digits(*args) ⇒ Calc::Q

Returns the number of digits of the integral part of self in decimal or another base

Note that this is unlike the ruby’s ‘Integer#digits`. For an equivalent, see `Q#digits_r`.

Examples:

Calc::Q("12.3456").digits   #=> Calc::Q(2)
Calc::Q(-1234).digits       #=> Calc::Q(4)
Calc::Q(0).digits           #=> Calc::Q(1)
Calc::Q("-0.123").digits    #=> Calc::Q(1)

Parameters:

  • b (Integer)

    (optional) base >= 2 (default 10)

Returns:



1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
# File 'ext/calc/q.c', line 1119

static VALUE
cq_digits(int argc, VALUE * argv, VALUE self)
{
    VALUE base;
    NUMBER *qbase, *qresult;
    long n;
    setup_math_error();

    n = rb_scan_args(argc, argv, "01", &base);
    if (n >= 1) {
        qbase = value_to_number(base, 1);
        if (qisfrac(qbase) || qiszero(qbase) || qisunit(qbase)) {
            qfree(qbase);
            rb_raise(e_MathError, "base must be integer greater than 1 for digits");
        }
    }
    qresult = itoq(qdigits(DATA_PTR(self), n >= 1 ? qbase->num : _ten_));
    if (n >= 1)
        qfree(qbase);
    return wrap_number(qresult);
}

#digits_r(b = 10) ⇒ Array

Returns an array of digits in base b making up self

This is compatible with ruby’s ‘Integer#digits`. Note that `Q#digits` implements the libcalc function `digits`, which is different. Any fractional part of self is truncated.

Requires ruby 2.4.

Examples:

Calc::Q(1234).digits_r      #=> [Calc::Q(4), Calc::Q(3), Calc::Q(2), Calc::Q(1)]
Calc::Q(1234).digits_r(7)   #=> [Calc::Q(2), Calc::Q(1), Calc::Q(4), Calc::Q(3)]
Calc::Q(1234).digits_r(100) #=> [Calc::Q(34), Calc::Q(12)]

Parameters:

  • b (Integer) (defaults to: 10)

    (optional) base, default 10

Returns:

  • (Array)


140
141
142
# File 'lib/calc/q.rb', line 140

def digits_r(b = 10)
  to_i.digits(b).map { |d| Q.new(d) }
end

#div(y) ⇒ Object

Ruby compatible integer division

Calls ‘quo` to get the quotient of integer division, with rounding mode which specifies behaviour compatible with ruby’s Numeric#div

Examples:

Calc::Q(13).div(4)     #=> Calc::Q(3)
Calc::Q("11.5").div(4) #=> Calc::Q(2)

Parameters:

See Also:

  • #quo


155
156
157
# File 'lib/calc/q.rb', line 155

def div(y)
  quo(y, ZERO)
end

#divmod(y) ⇒ Object

Ruby compatible quotient/modulus

Returns an array containing the quotient and modulus by dividing ‘self` by `y`. Rounding is compatible with the ruby method `Numeric#divmod`.

Unlike ‘quomod`, this is not affected by `Calc.config(:quomod)`.

Examples:

Calc::Q(11).divmod(3)  #=> [Calc::Q(3), Calc::Q(2)]
Calc::Q(11).divmod(-3) #=> [Calc::Q(-4), Calc::Q(-1)]

Parameters:



170
171
172
# File 'lib/calc/q.rb', line 170

def divmod(y)
  quomod(y, ZERO)
end

#downto(limit, &block) ⇒ Enumerator?

Iterates the given block, yielding values from ‘self` decreasing by 1 down to and including `limit`

x.downto(limit) is equivalent to x.step(by: -1, to: limit)

If no block is given, an Enumerator is returned instead.

Examples:

Calc::Q(10).downto(5) { |i| print i, " " } #=> 10 9 8 7 6 5

Parameters:

  • limit (Numeric)

    lowest value to return

Returns:

  • (Enumerator, nil)


185
186
187
# File 'lib/calc/q.rb', line 185

def downto(limit, &block)
  step(limit, NEGONE, &block)
end

#estrString

Returns a string which if evaluated creates a new object with the original value

Examples:

Calc::Q(0.5).estr #=> "Calc::Q(1,2)"

Returns:

  • (String)


194
195
196
197
198
199
200
# File 'lib/calc/q.rb', line 194

def estr
  s = self.class.name
  s << "("
  s << (int? ? num.to_s : "#{ num },#{ den }")
  s << ")"
  s
end

#eulerObject

Euler number

Returns the euler number of a specified index.

Considerable runtime and memory are required for calculating the euler number for large even indices. Calculated values are stored in a table so that later calls are executed quickly. This memory can be freed with ‘Calc.freeeuler`.

Examples:

Calc::Q(18).euler   #=> Calc::Q(-2404879675441)
Calc::Q(19).euler   #=> Calc::Q(0)
Calc::Q(20).euler   #=> Calc::Q(370371188237525)


1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
# File 'ext/calc/q.c', line 1155

static VALUE
cq_euler(VALUE self)
{
    NUMBER *qself, *qresult;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisfrac(qself)) {
        rb_raise(e_MathError, "non-integer value for euler");
    }
    qresult = qeuler(qself->num);
    if (qresult == NULL) {
        rb_raise(e_MathError, "number too big or out of memory for euler");
    }
    return wrap_number(qresult);
}

#even?Boolean

Returns true if the number is an even integer

Examples:

Calc::Q(1).even? #=> false
Calc::Q(2).even? #=> true

Returns:

  • (Boolean)


1179
1180
1181
1182
1183
# File 'ext/calc/q.c', line 1179

static VALUE
cq_evenp(VALUE self)
{
    return qiseven((NUMBER *) DATA_PTR(self)) ? Qtrue : Qfalse;
}

#exp(*args) ⇒ Calc::Q

Exponential function

Examples:

Calc::Q(1).exp #=> Calc::Q(2.71828182845904523536)
Calc::Q(2).exp #=> Calc::Q(7.38905609893065022723)

Parameters:

Returns:



1193
1194
1195
1196
1197
# File 'ext/calc/q.c', line 1193

static VALUE
cq_exp(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qexp, NULL);
}

#factCalc::Q

Returns the factorial of a number.

@example:

Calc::Q(10).fact #=> Calc::Q(3628800)

Returns:

Raises:



1207
1208
1209
1210
1211
1212
# File 'ext/calc/q.c', line 1207

static VALUE
cq_fact(VALUE self)
{
    setup_math_error();
    return wrap_number(qfact(DATA_PTR(self)));
}

#factor(*args) ⇒ Calc::Q

Smallest prime factor not exceeding specified limit

Ignoring signs of self and limit; if self has a prime factor less than or equal to limit, then returns the smallest such factor.

Examples:

Calc::Q(2).power(32).+(1).factor #=> Calc::Q(641)

Parameters:

  • limit (Numeric)

    (optional) limit, defaults to 2^32-1

Returns:

Raises:



1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
# File 'ext/calc/q.c', line 1226

static VALUE
cq_factor(int argc, VALUE * argv, VALUE self)
{
    VALUE limit;
    NUMBER *qself, *qlimit, *qfactor;
    ZVALUE zlimit;
    long a;
    int res;
    setup_math_error();

    a = rb_scan_args(argc, argv, "01", &limit);
    if (a >= 1) {
        qlimit = value_to_number(limit, 0);
        if (qisfrac(qlimit)) {
            qfree(qlimit);
            rb_raise(e_MathError, "non-integer limit for factor");
        }
        zcopy(qlimit->num, &zlimit);
        qfree(qlimit);
    }
    else {
        /* default limit is 2^32-1 */
        utoz((FULL) 0xffffffff, &zlimit);
    }
    qself = DATA_PTR(self);
    if (qisfrac(qself)) {
        zfree(zlimit);
        rb_raise(e_MathError, "non-integer for factor");
    }

    qfactor = qalloc();
    res = zfactor(qself->num, zlimit, &(qfactor->num));
    if (res < 0) {
        qfree(qfactor);
        zfree(zlimit);
        rb_raise(e_MathError, "limit >= 2^32 for factor");
    }
    zfree(zlimit);
    return wrap_number(qfactor);
}

#fcnt(y) ⇒ Calc::Q

Count number of times an integer divides self.

Returns the greatest non-negative n for which y^n is a divisor of self. Zero is returns if self is not divisible by y.

Examples:

Calc::Q(24).fcnt(4) #=> Calc::Q(1)
Calc::Q(48).fcnt(4) #=> Calc::Q(2)

Parameters:

  • y (Integer)

Returns:

Raises:



1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
# File 'ext/calc/q.c', line 1279

static VALUE
cq_fcnt(VALUE self, VALUE y)
{
    VALUE result;
    NUMBER *qself, *qy;
    setup_math_error();

    qself = DATA_PTR(self);
    qy = value_to_number(y, 0);
    if (qisfrac(qself) || qisfrac(qy)) {
        qfree(qy);
        rb_raise(e_MathError, "non-integral argument for fcnt");
    }
    result = wrap_number(itoq(zdivcount(qself->num, qy->num)));
    qfree(qy);
    return result;
}

#fibCalc::Q

Returns the Fibonacci number with index self.

Examples:

Calc::Q(10).fib #=> Calc::Q(55)

Returns:

Raises:



1349
1350
1351
1352
1353
1354
# File 'ext/calc/q.c', line 1349

static VALUE
cq_fib(VALUE self)
{
    setup_math_error();
    return wrap_number(qfib(DATA_PTR(self)));
}

#fracCalc::Q

Return the fractional part of self

Examples:

Calc::Q(22,7).frac.to_s(:frac) #=> "1/7"

Returns:



1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
# File 'ext/calc/q.c', line 1303

static VALUE
cq_frac(VALUE self)
{
    NUMBER *qself;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisint(qself)) {
        return wrap_number(qlink(&_qzero_));
    }
    else {
        return wrap_number(qfrac(qself));
    }
}

#frem(y) ⇒ Calc::Q

Remove specified integer factors from self.

Examples:

Calc::Q(7).frem(4)   #=> 7
Calc::Q(24).frem(4)  #=> 6
Calc::Q(48).frem(4)  #=> 3
Calc::Q(-48).frem(4) #=> 3

Parameters:

  • y (Integer)

Returns:

Raises:



1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
# File 'ext/calc/q.c', line 1329

static VALUE
cq_frem(VALUE self, VALUE y)
{
    VALUE result;
    NUMBER *qy;

    qy = value_to_number(y, 0);
    result = wrap_number(qfacrem(DATA_PTR(self), qy));
    qfree(qy);
    return result;
}

#gcd(*args) ⇒ Calc::Q

Greatest common divisor

Returns the greatest common divisor of self and all arguments. If no arguments, returns self.

Examples:

Calc::Q(12).gcd(8)               #=> Calc::Q(4)
Calc::Q(12).gcd(8, 6)            #=> Calc::Q(2)
Calc.gcd("9/10", "11/5", "4/25") #=> Calc::Q(0.02)

Returns:



1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
# File 'ext/calc/q.c', line 1367

static VALUE
cq_gcd(int argc, VALUE * argv, VALUE self)
{
    NUMBER *qresult, *qarg, *qtmp;
    int i;
    setup_math_error();

    qresult = qqabs(DATA_PTR(self));
    for (i = 0; i < argc; i++) {
        qarg = value_to_number(argv[i], 1);
        qtmp = qgcd(qresult, qarg);
        qfree(qarg);
        qfree(qresult);
        qresult = qtmp;
    }
    return wrap_number(qresult);
}

#gcdlcm(*args) ⇒ Array

Returns an array; [gcd, lcm]

This method exists for compatibility with ruby’s Integer class, however note that the libcalc version works on rational numbers and the lcm can be negative. You can also pass more than one value.

Examples:

Calc::Q(2).gcdlcm(2)  #=> [Calc::Q(2), Calc::Q(2)]
Calc::Q(3).gcdlcm(-7) #=> [Calc::Q(1), Calc::Q(-21)]

Returns:

  • (Array)


212
213
214
# File 'lib/calc/q.rb', line 212

def gcdlcm(*args)
  [gcd(*args), lcm(*args)]
end

#gcdrem(other) ⇒ Calc::Q

Returns greatest integer divisor of self relatively prime to other

Examples:

Calc::Q(6).gcdrem(15) #=> Calc::Q(2)
Calc::Q(15).gcdrem(6) #=> Calc::Q(5)

Returns:



1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
# File 'ext/calc/q.c', line 1392

static VALUE
cq_gcdrem(VALUE self, VALUE other)
{
    NUMBER *qother, *qresult;
    setup_math_error();

    qother = value_to_number(other, 0);
    qresult = qgcdrem(DATA_PTR(self), qother);
    qfree(qother);
    return wrap_number(qresult);
}

#gd(*args) ⇒ Calc::Q

Gudermannian function

Examples:

Calc::Q(1).gd #=> Calc::Q(0.86576948323965862429)

Parameters:

  • eps (Calc::Q)

    (optional) calculation accuracy

Returns:



222
223
224
225
# File 'lib/calc/q.rb', line 222

def gd(*args)
  r = Calc::C(self).gd(*args)
  r.real? ? r.re : r
end

#highbitCalc::Q

Returns index of highest bit in binary representation of self

If self is a non-zero integer, higbit returns the index of the highest bit in the binary representation of abs(self). Equivalently, x.highbit = n if 2^n <= abs(x) < 2^(n+1); the binary representation of x then has n + 1 digits.

Examples:

Calc::Q(4).highbit        #=> Calc::Q(2)
Calc::Q(2).**(27).highbit #=> Calc::Q(27)

Returns:



1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
# File 'ext/calc/q.c', line 1416

static VALUE
cq_highbit(VALUE self)
{
    NUMBER *qself;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisfrac(qself)) {
        rb_raise(e_MathError, "non-integer argument for highbit");
    }
    if (qiszero(qself)) {
        return wrap_number(qlink(&_qnegone_));
    }
    else {
        return wrap_number(itoq(zhighbit(qself->num)));
    }
}

#hypot(*args) ⇒ Calc::Q

Returns the hypotenuse of a right-angled triangle given the other sides

@example:

Calc::Q(3).hypot(4)  #=> Calc::Q(5)
Calc::Q(2).hypot(-3) #=> Calc::Q(3.60555127546398929312)

Parameters:

Returns:



1442
1443
1444
1445
1446
# File 'ext/calc/q.c', line 1442

static VALUE
cq_hypot(int argc, VALUE * argv, VALUE self)
{
    return trans_function2(argc, argv, self, &qhypot);
}

#iCalc::C

Returns the corresponding imaginary number

Examples:

Calc::Q(1).i #=> Calc::C(1i)

Returns:



232
233
234
# File 'lib/calc/q.rb', line 232

def i
  Calc::C(ZERO, self)
end

#imObject Also known as: imaginary, imag



236
237
238
# File 'lib/calc/q.rb', line 236

def im
  ZERO
end

#imag?Boolean

Returns true if the number is imaginary. Instances of this class always return false.

Examples:

Calc::Q(1).imag? #=> false

Returns:

  • (Boolean)


247
248
249
# File 'lib/calc/q.rb', line 247

def imag?
  false
end

#initialize_copy(orig) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'ext/calc/q.c', line 121

static VALUE
cq_initialize_copy(VALUE obj, VALUE orig)
{
    NUMBER *qorig, *qobj;

    if (obj == orig) {
        return obj;
    }
    if (!CALC_Q_P(orig)) {
        rb_raise(rb_eTypeError, "wrong argument type");
    }

    qorig = DATA_PTR(orig);
    qobj = qlink(qorig);
    DATA_PTR(obj) = qobj;

    return obj;
}

#inspectObject



251
252
253
# File 'lib/calc/q.rb', line 251

def inspect
  "Calc::Q(#{ self })"
end

#intCalc::Q

Integer part of the number

Examples:

Calc::Q(3).int      #=> Calc::Q(3)
Calc::Q("30/7").int #=> Calc::Q(4)
Calc::Q(-3.125).int #=> Calc::Q(-3)

Returns:



1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
# File 'ext/calc/q.c', line 1456

static VALUE
cq_int(VALUE self)
{
    NUMBER *qself;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisint(qself)) {
        return self;
    }
    return wrap_number(qint(qself));
}

#int?Boolean Also known as: integer?

Returns true if the number is an integer.

Examples:

Calc::Q(2).int?     #=> true
Calc::Q(0.1).int?   #=> false

Returns:

  • (Boolean)


1476
1477
1478
1479
1480
# File 'ext/calc/q.c', line 1476

static VALUE
cq_intp(VALUE self)
{
    return qisint((NUMBER *) DATA_PTR(self)) ? Qtrue : Qfalse;
}

#inverseCalc::Q

Inverse of a real number

@example:

Calc::Q(3).inverse #=> Calc::Q(0.25)

Returns:

Raises:



1489
1490
1491
1492
1493
1494
# File 'ext/calc/q.c', line 1489

static VALUE
cq_inverse(VALUE self)
{
    setup_math_error();
    return wrap_number(qinv(DATA_PTR(self)));
}

#iroot(other) ⇒ Calc::Q

Integer part of specified root

x.iroot(n) returns the greatest integer v for which v^n <= x.

Examples:

Calc::Q(100).iroot(3) #=> Calc::Q(4)

Parameters:

  • n (Integer)

Returns:

Raises:



1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
# File 'ext/calc/q.c', line 1506

static VALUE
cq_iroot(VALUE self, VALUE other)
{
    NUMBER *qother, *qresult;
    setup_math_error();

    qother = value_to_number(other, 0);
    qresult = qiroot(DATA_PTR(self), qother);
    qfree(qother);
    return wrap_number(qresult);
}

#isevenObject



255
256
257
# File 'lib/calc/q.rb', line 255

def iseven
  even? ? ONE : ZERO
end

#isimagCalc::Q

Returns 1 if the number is imaginary, otherwise returns 0. Instance of this class always return 0.

Examples:

Calc::Q(1).isimag #=> Calc::Q(0)

Returns:



265
266
267
# File 'lib/calc/q.rb', line 265

def isimag
  ZERO
end

#ismult(y) ⇒ Calc::Q

Returns 1 if self exactly divides y, otherwise return 0.

Examples:

Calc::Q(6).ismult(2) #=> Calc::Q(1)
Calc::Q(2).ismult(6) #=> Calc::Q(0)

Returns:

See Also:



276
277
278
# File 'lib/calc/q.rb', line 276

def ismult(y)
  mult?(y) ? ONE : ZERO
end

#isoddObject



280
281
282
# File 'lib/calc/q.rb', line 280

def isodd
  odd? ? ONE : ZERO
end

#isprimeCalc::Q

Returns 1 if self is prime, 0 if it is not prime. This function can’t be used for odd numbers > 2^32.

Examples:

Calc::Q(2**31 - 9).isprime #=> Calc::Q(0)
Calc::Q(2**31 - 1).isprime #=> Calc::Q(1)

Returns:

Raises:



292
293
294
# File 'lib/calc/q.rb', line 292

def isprime
  prime? ? ONE : ZERO
end

#isqrtCalc::Q

Integer part of square root

x.isqrt returns the greatest integer n for which n^2 <= x.

Examples:

Calc::Q("8.5").isqrt #=> Calc::Q(2)
Calc::Q(200).isqrt   #=> Calc::Q(14)
Calc::Q("2e6").isqrt #=> Calc::Q(1414)

Returns:

Raises:



1529
1530
1531
1532
1533
1534
# File 'ext/calc/q.c', line 1529

static VALUE
cq_isqrt(VALUE self)
{
    setup_math_error();
    return wrap_number(qisqrt(DATA_PTR(self)));
}

#isrealCalc::Q

Returns 1 if this number has zero imaginary part, otherwise returns 0. Instances of this class always return 1.

Examples:

Calc::Q(1).isreal #=> Calc::Q(1)

Returns:



302
303
304
# File 'lib/calc/q.rb', line 302

def isreal
  ONE
end

#isrel(y) ⇒ Calc::Q

Returns 1 if both values are relatively prime

Examples:

Calc::Q(6).isrel(5) #=> Calc::Q(1)
Calc::Q(6).isrel(2) #=> Calc::Q(0)

Parameters:

  • other (Integer)

Returns:

Raises:

See Also:



315
316
317
# File 'lib/calc/q.rb', line 315

def isrel(y)
  rel?(y) ? ONE : ZERO
end

#issqCalc::Q

Returns 1 if this value is a square

Examples:

Calc::Q(25).issq     #=> Calc::Q(1)
Calc::Q(3).issq      #=> Calc::Q(0)
Calc::Q("4/25").issq #=> Calc::Q(1)

Returns:

See Also:



327
328
329
# File 'lib/calc/q.rb', line 327

def issq
  sq? ? ONE : ZERO
end

#jacobi(y) ⇒ Calc::Q

Compute the Jacobi function (x = self / y)

Returns: -1 if x is not quadratic residue mod y

1 if y is composite, or x is a quadratic residue of y]
0 if y is even or y is < 0

Examples:

Calc::Q(2).jacobi(5)  #=> Calc::Q(-1)
Calc::Q(2).jacobi(15) #=> Calc::Q(1)

Parameters:

  • y (Integer)

Returns:

Raises:



1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
# File 'ext/calc/q.c', line 1550

static VALUE
cq_jacobi(VALUE self, VALUE y)
{
    NUMBER *qy, *qresult;
    setup_math_error();

    qy = value_to_number(y, 0);
    qresult = qjacobi(DATA_PTR(self), qy);
    qfree(qy);
    return wrap_number(qresult);
}

#lcm(*args) ⇒ Calc::Q

Least common multiple

If no value is zero, lcm returns the least positive number which is a multiple of all values. If at least one value is zero, the lcm is zero.

Examples:

Calc::Q(12).lcm(24, 30) #=> Calc::Q(120)

Parameters:

  • v (Numeric)

    zero or more values

Returns:



1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
# File 'ext/calc/q.c', line 1572

static VALUE
cq_lcm(int argc, VALUE * argv, VALUE self)
{
    NUMBER *qresult, *qarg, *qtmp;
    int i;
    setup_math_error();

    qresult = qqabs(DATA_PTR(self));
    for (i = 0; i < argc; i++) {
        qarg = value_to_number(argv[i], 1);
        qtmp = qlcm(qresult, qarg);
        qfree(qarg);
        qfree(qresult);
        qresult = qtmp;
        if (qiszero(qresult))
            break;
    }
    return wrap_number(qresult);
}

#lcmfactCalc::Q

Least common multiple of positive integers up to specified integer

Retrurns the lcm of the integers 1, 2, …, self

Examples:

Calc::Q(6).lcmfact #=> Calc::Q(60)
Calc::Q(7).lcmfact #=> Calc::Q(420)

Returns:



1601
1602
1603
1604
1605
1606
# File 'ext/calc/q.c', line 1601

static VALUE
cq_lcmfact(VALUE self)
{
    setup_math_error();
    return wrap_number(qlcmfact(DATA_PTR(self)));
}

#lfactor(other) ⇒ Calc::Q

Smallest prime factor in first specified number of primes

If n is nonzero and abs(n) has a prime factor in the first m primes (2, 3, 5, …), then n.lfactor(m) returns the smallest such factor. Otherwise it returns 1.

Examples:

Calc::Q(2**32 + 1).lfactor(116) #=> Calc::Q(641)

Parameters:

Returns:



1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
# File 'ext/calc/q.c', line 1619

static VALUE
cq_lfactor(VALUE self, VALUE other)
{
    NUMBER *qother, *qresult;
    setup_math_error();

    qother = value_to_number(other, 1);
    qresult = qlowfactor(DATA_PTR(self), qother);
    qfree(qother);
    return wrap_number(qresult);
}

#lowbitCalc::Q

Index of lowest nonzero bit in binary representation

Returns the index of the lowest nonzero bit in the binary representation of abs(self). If self is zero, returns -1.

Examples:

Calc::Q(2).lowbit     #=> Calc::Q(1)
Calc::Q(2**27).lowbit #=> Calc::Q(27)

Returns:

Raises:



1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
# File 'ext/calc/q.c', line 1642

static VALUE
cq_lowbit(VALUE self)
{
    NUMBER *qself;
    long index;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qiszero(qself)) {
        index = -1;
    }
    else if (qisfrac(qself)) {
        rb_raise(e_MathError, "non-integer argument for lowbit");
    }
    else {
        index = zlowbit(qself->num);
    }
    return wrap_number(itoq(index));
}

#ltol(*args) ⇒ Calc::Q

leg-to-leg - third side of a right angled triangle

Returns the third side of a right-angled triangle with unit hypotenuse, given one other side. x.ltol is equivalent to sqrt(1 - x**2). Result is to nearest multiple of eps which defaults to Calc.config(:epsilon).

Examples:

Calc::Q("0.5").ltol #=> Calc::Q(0.86602540378443864676)

Parameters:

  • eps (Numeric)

    (optional) calculation accuracy

Returns:

Raises:



1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
# File 'ext/calc/q.c', line 1674

static VALUE
cq_ltol(int argc, VALUE * argv, VALUE self)
{
    VALUE epsilon;
    NUMBER *qresult, *qepsilon;
    setup_math_error();

    if (rb_scan_args(argc, argv, "01", &epsilon) == 0) {
        qresult = qlegtoleg(DATA_PTR(self), conf->epsilon, FALSE);
    }
    else {
        qepsilon = value_to_number(epsilon, 1);
        qresult = qlegtoleg(DATA_PTR(self), qepsilon, FALSE);
        qfree(qepsilon);
    }
    return wrap_number(qresult);
}

#meq(y, md) ⇒ Calc::Q

test for equaility modulo a specific number

Returns 1 if self is congruent to y modulo md, otherwise 0.

Examples:

Calc::Q(5).meq(33, 7) #=> Calc::Q(1)
Calc::Q(5).meq(32, 7) #=> Calc::Q(0)

Parameters:

Returns:

See Also:



342
343
344
# File 'lib/calc/q.rb', line 342

def meq(y, md)
  meq?(y, md) ? ONE : ZERO
end

#meq?(y, md) ⇒ Boolean

test for equality modulo a specific number

Returns true if self is congruent to y modulo md.

Examples:

Calc::Q(5).meq?(33, 7) #=> true
Calc::Q(5).meq?(32, 7) #=> false

Parameters:

Returns:

  • (Boolean)

See Also:



1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
# File 'ext/calc/q.c', line 1704

static VALUE
cq_meqp(VALUE self, VALUE y, VALUE md)
{
    VALUE result;
    NUMBER *qy, *qmd, *qtmp;
    setup_math_error();

    qy = value_to_number(y, 1);
    qmd = value_to_number(md, 1);
    qtmp = qsub(DATA_PTR(self), qy);
    result = qdivides(qtmp, qmd) ? Qtrue : Qfalse;
    qfree(qtmp);
    qfree(qmd);
    qfree(qy);
    return result;
}

#minv(md) ⇒ Calc::Q

Inverse of an integer modulo a specified integer

Finds x such that:

self * x = 1 (mod md)

If self and md are not relatively prime, zero is returned.

The canonical residues modulo md are determined by Calc.config(:mod) (run “help minv” in calc for details).

Examples:

Calc::Q(3).minv(10)  #=> Calc::Q(7)
Calc::Q(-3).minv(10) #=> Calc::Q(3)

Parameters:

  • md (Integer)

Returns:

Raises:



1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
# File 'ext/calc/q.c', line 1737

static VALUE
cq_minv(VALUE self, VALUE md)
{
    NUMBER *qmd, *qresult;
    setup_math_error();

    qmd = value_to_number(md, 1);
    qresult = qminv(DATA_PTR(self), qmd);
    qfree(qmd);
    return wrap_number(qresult);
}

#mne(y, md) ⇒ Calc::Q

test for inequality modulo a specific number

Reurns 1 if self is not congruent to y modulo md, otherwise 0. This is the opposite of #meq.

Examples:

Calc::Q(5).mne(33, 7) #=> Calc::Q(0)
Calc::Q(5).mne(32, 7) #=> Calc::Q(1)

Parameters:

Returns:

See Also:



358
359
360
# File 'lib/calc/q.rb', line 358

def mne(y, md)
  meq?(y, md) ? ZERO : ONE
end

#mne?(y, md) ⇒ Boolean

test for inequality modulo a specific number

Returns true of self is not congruent to y modulo md. This is the opposiute of #meq?.

Examples:

Calc::Q(5).mne?(33, 7) #=> false
Calc::Q(5).mne?(32, 6) #=> true

Parameters:

Returns:

  • (Boolean)


373
374
375
# File 'lib/calc/q.rb', line 373

def mne?(y, md)
  !meq?(y, md)
end

#mod(*args) ⇒ Calc::Q

Computes the remainder for an integer quotient

@example:

Calc::Q(11).mod(5) #=> Calc::Q(1)

Parameters:

  • y (Numeric, Calc::Q)
  • rnd (Integer)

    rounding flags (default Calc.config(:mod))

Returns:



1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
# File 'ext/calc/q.c', line 1757

static VALUE
cq_mod(int argc, VALUE * argv, VALUE self)
{
    VALUE other, rnd;
    NUMBER *qother, *qresult;
    long n;
    setup_math_error();

    n = rb_scan_args(argc, argv, "11", &other, &rnd);
    qother = value_to_number(other, 0);
    if (qiszero(qother)) {
        qfree(qother);
        rb_raise(rb_eZeroDivError, "division by zero in mod");
    }
    qresult = qmod(DATA_PTR(self), qother, (n == 2) ? value_to_long(rnd) : conf->mod);
    qfree(qother);
    return wrap_number(qresult);
}

#modulo(y) ⇒ Object

Ruby compatible modulus

Returns the modulus of ‘self` divided by `y`.

Rounding is compatible with the ruby method Numeric#modulo. Unlike ‘mod`, this is not affected by `Calc.confg(:mod)`.

Examples:

Calc::Q(13).modulo(4)  #=> Calc::Q(1)
Calc::Q(13).modulo(-4) #=> Calc::Q(-3)

Parameters:



388
389
390
# File 'lib/calc/q.rb', line 388

def modulo(y)
  mod(y, ZERO)
end

#mult?(other) ⇒ Boolean

Returns true if self exactly divides y, otherwise return false.

Examples:

Calc::Q(6).mult?(2) #=> true
Calc::Q(2).mult?(6) #=> false

Returns:

  • (Boolean)

See Also:



1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
# File 'ext/calc/q.c', line 1784

static VALUE
cq_multp(VALUE self, VALUE other)
{
    VALUE result;
    NUMBER *qother;
    setup_math_error();

    qother = value_to_number(other, 0);
    result = qdivides(DATA_PTR(self), qother) ? Qtrue : Qfalse;
    qfree(qother);
    return result;
}

#near(*args) ⇒ Calc::Q

Compare nearness of two numbers with a standard

Returns:

-1 if abs(self - other) < abs(eps)
 0 if abs(self - other) = abs(eps)
 1 if abs(self - other) > abs(eps)

Examples:

Calc::Q("22/7").near("3.15", ".01")  #=> Calc::Q(-1)
Calc::Q("22/7").near("3.15", ".005") #=> Calc::Q(1)

Parameters:

  • other (Numeric)
  • eps (Numeric)

    (optional) defaults to Calc.config(:epsilon)

Returns:



1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
# File 'ext/calc/q.c', line 1811

static VALUE
cq_near(int argc, VALUE * argv, VALUE self)
{
    VALUE other, epsilon;
    NUMBER *qother, *qepsilon, *qresult;
    int n;
    setup_math_error();

    n = rb_scan_args(argc, argv, "11", &other, &epsilon);
    qother = value_to_number(other, 1);
    qepsilon = (n == 2) ? value_to_number(epsilon, 1) : conf->epsilon;
    qresult = itoq((long) qnear(DATA_PTR(self), qother, qepsilon));
    qfree(qother);
    if (n == 2)
        qfree(qepsilon);
    return wrap_number(qresult);
}

#negative?Boolean

Return true if ‘self` is less than zero.

This method exists for ruby Integer/Rational compatibility

Examples:

Calc::Q(-1).negative? #=> true
Calc::Q(0).negative?  #=> false
Calc::Q(1).negative?  #=> false

Returns:

  • (Boolean)


401
402
403
# File 'lib/calc/q.rb', line 401

def negative?
  self < ZERO
end

#nextcand(*args) ⇒ Calc::Q

Next candidate for primeness

Returns the least positive integer i greater than abs(self) expressible as residue + k * modulus, where k is an integer, for which i.ptest?(count, skip) is true, or if there is no such integer i, nil.

See ‘ptest?` for a description of `count` and `skip`. For basic purposes, use default values and count > 1. Higher counts increase the probability that the returned value is prime.

Examples:

Calc::Q(100).nextcand(10)        #=> Calc::Q(101)
Calc::Q(5000000000).nextcand(10) #=> Calc::Q(5000000029)

Parameters:

  • count (Integer)

    number of tests for ptest (default 1)

  • skip (Integer)

    base selection mode for ptest (default 1)

  • residue (Integer)

    (default 0)

  • modulus (Integer)

    (default 1)

Returns:

Raises:



1849
1850
1851
1852
1853
# File 'ext/calc/q.c', line 1849

static VALUE
cq_nextcand(int argc, VALUE * argv, VALUE self)
{
    return cand_navigation(argc, argv, self, &znextcand);
}

#nextprimeCalc::Q

Next prime number

If self is >= 2**32, raises an exception. Otherwise returns the next prime number.

Examples:

Calc::Q(2).nextprime         #=> Calc::Q(3)
Calc::Q(10).nextprime        #=> Calc::Q(11)
Calc::Q(100).nextprime       #=> Calc::Q(101)
Calc::Q("1e6").nextprime     #=> Calc::Q(1000003)
Calc::Q(2**32 - 1).nextprime #=> Calc::Q(4294967311)

Returns:

Raises:



1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
# File 'ext/calc/q.c', line 1872

static VALUE
cq_nextprime(VALUE self)
{
    NUMBER *qself;
    FULL next_prime;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisfrac(qself)) {
        rb_raise(e_MathError, "non-integral for nextprime");
    }
    next_prime = znprime(qself->num);
    if (next_prime == 0) {
        /* return 2^32+15 */
        return wrap_number(qlink(&_nxtprime_));
    }
    else if (next_prime == 1) {
        rb_raise(e_MathError, "nextprime arg is >= 2^32");
    }
    return wrap_number(utoq(next_prime));
}

#normCalc::Q

Norm of a value

For real values, norm is the square of the absolute value.

Examples:

Calc::Q("3.4").norm  #=> Calc::Q(11.56)
Calc::Q("-3.4").norm #=> Calc::Q(11.56)

Returns:



1903
1904
1905
1906
1907
1908
# File 'ext/calc/q.c', line 1903

static VALUE
cq_norm(VALUE self)
{
    setup_math_error();
    return wrap_number(qsquare(DATA_PTR(self)));
}

#numCalc::Q Also known as: numerator

Returns the numerator. Return value has the same sign as self.

@example:

Calc::Q(1,3).num  #=> Calc::Q(1)
Calc::Q(-1,3).num #=> Calc::Q(-1)

Returns:



1917
1918
1919
1920
1921
1922
# File 'ext/calc/q.c', line 1917

static VALUE
cq_num(VALUE self)
{
    setup_math_error();
    return wrap_number(qnum(DATA_PTR(self)));
}

#odd?Boolean

Returns true if the number is an odd integer

Examples:

Calc::Q(1).odd? #=> true
Calc::Q(2).odd? #=> false

Returns:

  • (Boolean)


1931
1932
1933
1934
1935
# File 'ext/calc/q.c', line 1931

static VALUE
cq_oddp(VALUE self)
{
    return qisodd((NUMBER *) DATA_PTR(self)) ? Qtrue : Qfalse;
}

#ordCalc::Q

Returns self.

This method is for ruby Integer compatibility

Returns:



410
411
412
# File 'lib/calc/q.rb', line 410

def ord
  self
end

#perm(other) ⇒ Calc::Q

Permutation number

Returns the number of permutations in which ‘other` things may be chosen from `self` items where order in which they are chosen matters.

Examples:

Calc::Q(7).perm(3) #=> Calc::Q(210)

Parameters:

  • other (Integer)

Returns:



1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
# File 'ext/calc/q.c', line 1947

static VALUE
cq_perm(VALUE self, VALUE other)
{
    NUMBER *qresult, *qother;
    setup_math_error();

    qother = value_to_number(other, 0);
    qresult = qperm(DATA_PTR(self), qother);
    qfree(qother);
    return wrap_number(qresult);
}

#pfactCalc::Q

Product of primes up to specified integer

Examples:

Calc::Q(2).pfact   #=> Calc::Q(2)
Calc::Q(10).pfact  #=> Calc::Q(210)
Calc::Q(100).pfact #=> Calc::Q(2305567963945518424753102147331756070)

Returns:

Raises:



1968
1969
1970
1971
1972
1973
# File 'ext/calc/q.c', line 1968

static VALUE
cq_pfact(VALUE self)
{
    setup_math_error();
    return wrap_number(qpfact(DATA_PTR(self)));
}

#pixCalc::Q

Number of primes not exceeded specified number

Examples:

Calc::Q(10).pix    #=> Calc::Q(4)
Calc::Q(100).pix   #=> Calc::Q(25)
Calc::Q(10**9).pix #=> Calc::Q(50847534)

Returns:

Raises:



1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
# File 'ext/calc/q.c', line 1984

static VALUE
cq_pix(VALUE self)
{
    NUMBER *qself;
    long value;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisfrac(qself)) {
        rb_raise(e_MathError, "non-integer value for pix");
    }
    value = zpix(qself->num);
    if (value >= 0) {
        return wrap_number(utoq(value));
    }
    rb_raise(e_MathError, "pix arg is >= 2^32");
}

#places(*args) ⇒ Calc::Q

Number of decimal (or other) places in fractional part

Returns the number of digits needed to express the fractional part of this number in base b. If self is an integer, returns 0. If the expansion in base b is infinite, returns nil.

Examples:

Calc::Q(3).places           #=> Calc::Q(0)
Calc::Q("0.0123").places    #=> Calc::Q(4)
Calc::Q("0.0123").places(2) #=> nil
Calc::Q(".625").places(2)   #=> Calc::Q(3)

Parameters:

  • b (Integer)

    base (default 10)

Returns:

Raises:



2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
# File 'ext/calc/q.c', line 2017

static VALUE
cq_places(int argc, VALUE * argv, VALUE self)
{
    VALUE base;
    NUMBER *qbase;
    long places;
    setup_math_error();

    if (rb_scan_args(argc, argv, "01", &base) == 0) {
        places = qdecplaces(DATA_PTR(self));
    }
    else {
        qbase = value_to_number(base, 0);
        if (qisfrac(qbase)) {
            qfree(qbase);
            rb_raise(e_MathError, "non-integer base for places");
        }
        places = qplaces(DATA_PTR(self), qbase->num);
        qfree(qbase);
        if (places == -2) {
            rb_raise(e_MathError, "invalid base for places");
        }
    }
    if (places == -1) {
        return Qnil;
    }
    return wrap_number(itoq(places));
}

#pmod(n, md) ⇒ Calc::Q

Integral power of an interger modulo a specified integer

x.pmod(n, md) returns the integer value of the canonical reidue of x^n modulo md. The canonical residue is determined by Calc.config(:mod). See “help pmod” for full details.

Examples:

Calc::Q(2).pmod(3, 10) #=> Calc::Q(8)
Calc::Q(2).pmod(5, 10) #=> Calc::Q(2)

Parameters:

  • n (Integer)
  • md (Integer)

Returns:



2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
# File 'ext/calc/q.c', line 2059

static VALUE
cq_pmod(VALUE self, VALUE n, VALUE md)
{
    NUMBER *qn, *qmd, *qresult;
    setup_math_error();

    qn = value_to_number(n, 0);
    qmd = value_to_number(md, 0);
    qresult = qpowermod(DATA_PTR(self), qn, qmd);
    qfree(qn);
    qfree(qmd);
    return wrap_number(qresult);
}

#popcnt(*args) ⇒ Calc::Q

Number of bits that match 0 or 1

Counts of number of bits in abs(self) that match bitval (1 or 0, default 1)

Examples:

Calc::Q(32767).popcnt    #=> Calc::Q(15)
Calc::Q(32767).popcnt(0) #=> Calc::Q(0)

Parameters:

  • bitval (Integer)

    0 or 1 (default 1)

Returns:



2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
# File 'ext/calc/q.c', line 2083

static VALUE
cq_popcnt(int argc, VALUE * argv, VALUE self)
{
    VALUE bitval;
    NUMBER *qself, *qbitval, *qresult;
    int b = 1;
    setup_math_error();

    if (rb_scan_args(argc, argv, "01", &bitval) == 1) {
        qbitval = value_to_number(bitval, 0);
        if (qiszero(qbitval)) {
            b = 0;
        }
        qfree(qbitval);
    }
    qself = DATA_PTR(self);
    if (qisint(qself)) {
        qresult = itoq(zpopcnt(qself->num, b));
    }
    else {
        qresult = itoq(zpopcnt(qself->num, b) + zpopcnt(qself->den, b));
    }
    return wrap_number(qresult);
}

#positive?Boolean

Return true if ‘self` is greater than zero.

This method exists for ruby Integer/Rational compatibility

Examples:

Calc::Q(-1).positive? #=> false
Calc::Q(0).positive?  #=> false
Calc::Q(1).positive?  #=> true

Returns:

  • (Boolean)


423
424
425
# File 'lib/calc/q.rb', line 423

def positive?
  self > ZERO
end

#power(*args) ⇒ Calc::Q, Calc::C

Evaluates a numeric power

Examples:

Calc::Q("1.2345").power(10) #=> Calc::Q(8.2207405646327461795)
Calc::Q(-1).power("0.1")    #=> Calc::C(0.95105651629515357212+0.3090169943749474241i)

Parameters:

Returns:

Raises:



2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
# File 'ext/calc/q.c', line 2118

static VALUE
cq_power(int argc, VALUE * argv, VALUE self)
{
    /* ref: powervalue() in calc value.c.  handle cases NUM,NUM and NUM,COM */
    VALUE arg, epsilon, result;
    NUMBER *qself, *qarg, *qepsilon;
    COMPLEX *cself, *carg;
    setup_math_error();

    if (rb_scan_args(argc, argv, "11", &arg, &epsilon) == 1) {
        qepsilon = NULL;
    }
    else {
        qepsilon = value_to_number(epsilon, 1);
    }
    qself = DATA_PTR(self);
    if (CALC_C_P(arg) || RB_TYPE_P(arg, T_COMPLEX) || qisneg(qself)) {
        cself = comalloc();
        qfree(cself->real);
        cself->real = qlink(qself);
        if (RB_TYPE_P(arg, T_STRING)) {
            carg = comalloc();
            qfree(carg->real);
            carg->real = value_to_number(arg, 1);
        }
        else {
            carg = value_to_complex(arg);
        }
        result = wrap_complex(c_power(cself, carg, qepsilon ? qepsilon : conf->epsilon));
        comfree(cself);
        comfree(carg);
    }
    else {
        qarg = value_to_number(arg, 1);
        result = wrap_number(qpower(qself, qarg, qepsilon ? qepsilon : conf->epsilon));
        qfree(qarg)
    }
    if (qepsilon) {
        qfree(qepsilon);
    }
    return result;
}

#predCalc::Q

Returns one less than self.

This method exists for ruby Integer compatibility.

Examples:

Calc::Q(1).pred #=> Calc::Q(0)

Returns:



434
435
436
# File 'lib/calc/q.rb', line 434

def pred
  self - ONE
end

#prevcand(*args) ⇒ Calc::Q

Previous candidate for primeness

Returns the greatest positive integer i less than abs(self) expressible as residue + k * modulus, where k is an integer, for which ptest?(count, skip) is true, or if there is no such integer i, nil.

See ‘ptest?` for a description of `count` and `skip`. For basic purposes, use default values and count > 1. Higher counts increase the probability that the returned value is prime.

Examples:

Calc::Q(100).prevcand(10)        #=> Calc::Q(97)
Calc::Q(5000000000).prevcand(10) #=> Calc::Q(4999999937)

Parameters:

  • count (Integer)

    number of tests for ptest (default 1)

  • skip (Integer)

    base selection mode for ptest (default 1)

  • residue (Integer)

    (default 0)

  • modulus (Integer)

    (default 1)

Returns:

Raises:



2181
2182
2183
2184
2185
# File 'ext/calc/q.c', line 2181

static VALUE
cq_prevcand(int argc, VALUE * argv, VALUE self)
{
    return cand_navigation(argc, argv, self, &zprevcand);
}

#prevprimeCalc::Q

Previous prime number

If self <= 2, returns nil. If self is >= 2**32, raises an exception. Otherwise returns the previous prime number.

Examples:

Calc::Q(2).prevprime         #=> nil
Calc::Q(10).prevprime        #=> Calc::Q(7)
Calc::Q(100).prevprime       #=> Calc::Q(97)
Calc::Q("1e6").prevprime     #=> Calc::Q(999983)
Calc::Q(2**32 - 1).prevprime #=> Calc::Q(4294967291)

Returns:

Raises:



2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
# File 'ext/calc/q.c', line 2201

static VALUE
cq_prevprime(VALUE self)
{
    NUMBER *qself;
    FULL prev_prime;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisfrac(qself)) {
        rb_raise(e_MathError, "non-integral for prevprime");
    }
    prev_prime = zpprime(qself->num);
    if (prev_prime == 0) {
        return Qnil;
    }
    else if (prev_prime == 1) {
        rb_raise(e_MathError, "prevprime arg is >= 2^32");
    }
    return wrap_number(utoq(prev_prime));
}

#prime?Boolean

Small integer prime test

Returns true if self is prime, false if it is not prime. This function can’t be used for odd numbers > 2^32.

Examples:

Calc::Q(2**31 - 9).prime? #=> false
Calc::Q(2**31 - 1).prime? #=> true

Returns:

  • (Boolean)

Raises:

See Also:



2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
# File 'ext/calc/q.c', line 2234

static VALUE
cq_primep(VALUE self)
{
    NUMBER *qself;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisfrac(qself)) {
        rb_raise(e_MathError, "non-integral for prime?");
    }
    switch (zisprime(qself->num)) {
    case 0:
        return Qfalse;
    case 1:
        return Qtrue;
    default:
        rb_raise(e_MathError, "prime? argument is an odd value > 2^32");
    }
}

#ptest(*args) ⇒ Calc::Q

Probabilistic primacy test

Returns 1 if ptest? would have returned true, otherwise 0.

Parameters:

  • count (Integer)
  • skip (Integer)

Returns:

See Also:



446
447
448
# File 'lib/calc/q.rb', line 446

def ptest(*args)
  ptest?(*args) ? ONE : ZERO
end

#ptest?(*args) ⇒ Boolean

Probabilistic test of primality

Returns false if self is definitely not a prime. Returns true if self is probably prime.

If self is < 2**32, essentially calles prime? and returns true only if self is prime.

If self is > 2**32 and is divisible by a prime <= 101, returns false.

In other cases, performs abs(count) tests of bases of possible primality.

‘skip` specifies how to select bases for testing:

0: random in [2, self-2]
1: successive primes [2, 3, 5, ...] not exceeding min(self, 65536)
otherwise: integers starting from `skip`

For a full explanation of the tests, see “help ptest”.

Returning true from this function means self is either prime or a strong psuedoprime. The probability that a composite number returns true is less than (1/4)**count. For example, ptest(10) incorrectly returns true less than once in a million numbers; ptest(20) incorrectly returns true less than once in a quadrillion numbers.

Examples:

Calc::Q(4294967291).ptest?(10) #=> true

Parameters:

  • count (Integer)

    (optional: default 1)

  • skip (Integer)

    (optional: default 1)

Returns:

  • (Boolean)


2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
# File 'ext/calc/q.c', line 2285

static VALUE
cq_ptestp(int argc, VALUE * argv, VALUE self)
{
    VALUE count, skip, result;
    NUMBER *qcount, *qskip;
    int n;
    setup_math_error();

    n = rb_scan_args(argc, argv, "02", &count, &skip);
    qcount = (n >= 1) ? value_to_number(count, 0) : qlink(&_qone_);
    qskip = (n >= 2) ? value_to_number(skip, 0) : qlink(&_qone_);
    result = qprimetest(DATA_PTR(self), qcount, qskip) ? Qtrue : Qfalse;
    qfree(qcount);
    qfree(qskip);
    return result;
}

#quomod(*args) ⇒ Array<Calc::Q>

TODO:

add parameter to control rounding

Returns the quotient and remainder from division

Examples:

Calc::Q(13).quomod(5) #=> [Calc::Q(2), Calc::Q(3)]

Parameters:

  • y (Numeric, Calc::Q)

    number to divide by

  • rnd (Integer)

    optional rounding mode, default Calc.config(:quomod)

Returns:

  • (Array<Calc::Q>)

    Array containing quotient and remainder



2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
# File 'ext/calc/q.c', line 2311

static VALUE
cq_quomod(int argc, VALUE * argv, VALUE self)
{
    VALUE other, rnd;
    NUMBER *qother, *qquo, *qmod;
    long r;
    setup_math_error();

    if (rb_scan_args(argc, argv, "11", &other, &rnd) == 2) {
        r = value_to_long(rnd);
    }
    else {
        r = conf->quomod;
    }
    qother = value_to_number(other, 0);
    if (qiszero(qother)) {
        qfree(qother);
        rb_raise(rb_eZeroDivError, "division by zero in quomod");
    }
    qquomod(DATA_PTR(self), qother, &qquo, &qmod, r);
    qfree(qother);
    return rb_assoc_new(wrap_number(qquo), wrap_number(qmod));
}

#rationalize(eps = nil) ⇒ Calc::Q

Returns a simpler approximation of the value if the optional argument eps is given (rat-|eps| <= result <= rat+|eps|), self otherwise.

Note that this method exists for ruby Numeric compatibility. Libcalc has an alternative approximation method with different semantics, see ‘appr`.

Examples:

Calc::Q(5033165, 16777216).rationalize                   #=> Calc::Q(5033165/16777216)
Calc::Q(5033165, 16777216).rationalize(Rational('0.01')) #=> Calc::Q(3/10)
Calc::Q(5033165, 16777216).rationalize(Rational('0.1'))  #=> Calc::Q(1/3)

Parameters:

  • eps (Float, Rational) (defaults to: nil)

Returns:



462
463
464
# File 'lib/calc/q.rb', line 462

def rationalize(eps = nil)
  eps ? Q.new(to_r.rationalize(eps)) : self
end

#reObject Also known as: real



466
467
468
# File 'lib/calc/q.rb', line 466

def re
  self
end

#real?Boolean

Returns true if this number has zero imaginary part. Instances of this class always return true.

Examples:

Calc::Q(1).real? #=> true

Returns:

  • (Boolean)


476
477
478
# File 'lib/calc/q.rb', line 476

def real?
  true
end

#rel?(other) ⇒ Boolean

Returns true if both values are relatively prime

Examples:

Calc::Q(6).rel?(5) #=> true
Calc::Q(6).rel?(2) #=> false

Parameters:

  • other (Integer)

Returns:

  • (Boolean)

Raises:

See Also:



2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
# File 'ext/calc/q.c', line 2345

static VALUE
cq_relp(VALUE self, VALUE other)
{
    VALUE result;
    NUMBER *qself, *qother;
    setup_math_error();

    qself = DATA_PTR(self);
    qother = value_to_number(other, 0);
    if (qisfrac(qself) || qisfrac(qother)) {
        qfree(qother);
        rb_raise(e_MathError, "non-integer for rel?");
    }
    result = zrelprime(qself->num, qother->num) ? Qtrue : Qfalse;
    qfree(qother);
    return result;
}

#remainder(y) ⇒ Calc::C, Calc::Q

Remainder of ‘self` divided by `y`

This method is provided for compatibility with ruby’s ‘Numeric#remainder`. Unlike `%` and `mod`, this method behaves the same as the ruby version, unaffected by `Calc.config(:mod).

Examples:

Calc::Q(13).remainder(4) #=> Calc::Q(1)

Parameters:

Returns:



490
491
492
493
494
495
496
497
# File 'lib/calc/q.rb', line 490

def remainder(y)
  z = modulo(y)
  if !z.zero? && ((self < 0 && y > 0) || (self > 0 && y < 0))
    z - y
  else
    z
  end
end

#round(*args) ⇒ Calc::Q

Round to a specified number of decimal places

Rounds self rounded to the specified number of significant binary digits. For the meanings of the rounding flags, see “help round”.

Examples:

Calc::Q(7,32).round(3)  #=> Calc::Q(0.219)

Parameters:

  • places (Integer)

    number of decimal digits to round to (default 0)

  • rnd (Integer)

    rounding flags (default Calc.config(:round))

Returns:



2374
2375
2376
2377
2378
# File 'ext/calc/q.c', line 2374

static VALUE
cq_round(int argc, VALUE * argv, VALUE self)
{
    return rounding_function(argc, argv, self, &qround);
}

#sec(*args) ⇒ Calc::Q

Trigonometric secant

Examples:

Calc::Q(1).sec #=> Calc::Q(1.85081571768092561791)

Parameters:

Returns:



2387
2388
2389
2390
2391
# File 'ext/calc/q.c', line 2387

static VALUE
cq_sec(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qsec, NULL);
}

#sech(*args) ⇒ Calc::Q

Hyperbolic secant

Examples:

Calc::Q(1).sech #=> Calc::Q(0.64805427366388539958)

Parameters:

Returns:



2400
2401
2402
2403
2404
# File 'ext/calc/q.c', line 2400

static VALUE
cq_sech(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qsech, NULL);
}

#sin(*args) ⇒ Calc::Q

Trigonometric sine

Examples:

Calc::Q(1).sin #=> Calc::Q(0.84147098480789650665)

Parameters:

Returns:



2413
2414
2415
2416
2417
# File 'ext/calc/q.c', line 2413

static VALUE
cq_sin(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qsin, NULL);
}

#sinh(*args) ⇒ Calc::Q

Hyperbolic sine

Examples:

Calc::Q(1).sin #=> Calc::Q(1.17520119364380145688)

Parameters:

Returns:



2426
2427
2428
2429
2430
# File 'ext/calc/q.c', line 2426

static VALUE
cq_sinh(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qsinh, NULL);
}

#sizeCalc::Q

Returns the number of bytes in the machine representation of ‘self`

This method acts like ruby’s Integer#size, except that is works on fractions in which case the result is the number of bytes for both the numerator and denominator. As the internal representation of numbers differs between ruby and libcalc, it wil not necessary return the same values as Integer#size.

Examples:

Calc::Q(1).size     #=> Calc::Q(4)
Calc::Q(2**32).size #=> Calc::Q(8)
Calc::Q("1/3").size #=> Calc::Q(8)

Returns:



2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
# File 'ext/calc/q.c', line 2446

static VALUE
cq_size(VALUE self)
{
    NUMBER *qself;
    size_t s;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisint(qself)) {
        s = qself->num.len * sizeof(HALF);
    }
    else {
        s = (qself->num.len + qself->den.len) * sizeof(HALF);
    }
    return wrap_number(itoq(s));
}

#sq?Boolean

Return true if this value is a square

Returns true if there exists integers, b such that:

self == a^2 / b^2  (b != 0)

Note that this function works on rationals, so:

Calc::Q(25, 15).sq? #=> true

If you want to test for perfect square integers, you need to exclude non-integer values before you test.

Examples:

Calc::Q(25).sq?     #=> true
Calc::Q(3).sq?      #=> false
Calc::Q("4/25").sq? #=> true

Returns:

  • (Boolean)

See Also:



2481
2482
2483
2484
2485
2486
# File 'ext/calc/q.c', line 2481

static VALUE
cq_sqp(VALUE self)
{
    setup_math_error();
    return qissquare(DATA_PTR(self)) ? Qtrue : Qfalse;
}

#step(a1 = nil, a2 = ONE) ⇒ Enumerator?

Invokes the given block with the sequence of numbers starting at self incrementing by step (default 1) on each call.

In the first format, uses keyword parameters:

x.step(by: step, to: limit)

In the second format, uses positional parameters:

x.step(limit = nil, step = 1)

If step is negative, the sequence decrements instead of incrementing. If step is zero, the sequence will yield self forever.

If limit exists, the sequence will stop once the next item yielded would be higher than limit (if step is positive) or lower than limit (if step is negative). If limit is nil, the sequence never stops.

If no block is givem, an Enumerator is returned instead.

This method was added for ruby Numeric compatibiliy; unlike Numeric#step, it is not an error for step to be zero in the positional format.

prints:

2.71828182845904523536 2.91828182845904523536 3.11828182845904523536

Examples:

Calc::Q(1).step(10, 3).to_a      #=> [Calc::Q(1), Calc::Q(4), Calc::Q(7), Calc::Q(10)]
Calc::Q(10).step(by: -2).take(4) #=> [Calc::Q(10), Calc::Q(8), Calc::Q(6), Calc::Q(4)]
Calc::Q(1).exp.step(to: Calc.pi, by: "0.2") { |q| print q, " " } #=> nil

Parameters:

  • by (Numeric)

    amount to add to sequence each iteration

  • to (Numeric)

    end of sequence value

Returns:

  • (Enumerator, nil)


529
530
531
532
533
534
535
536
537
538
539
# File 'lib/calc/q.rb', line 529

def step(a1 = nil, a2 = ONE)
  return to_enum(:step, a1, a2) unless block_given?
  to, by = step_args(a1, a2)
  loop { yield self } if by.zero?
  i = self
  loop do
    break if to && ((by.positive? && i > to) || (by.negative? && i < to))
    yield i
    i += by
  end
end

#succCalc::Q Also known as: next

Returns one more than self.

This method exists for ruby Integer compatibility.

Examples:

Calc::Q(1).pred #=> Calc::Q(2)

Returns:



566
567
568
# File 'lib/calc/q.rb', line 566

def succ
  self + ONE
end

#tan(*args) ⇒ Calc::Q

Trigonometric tangent

Examples:

Calc::Q(1).tan #=> Calc::Q(1.55740772465490223051)

Parameters:

Returns:



2495
2496
2497
2498
2499
# File 'ext/calc/q.c', line 2495

static VALUE
cq_tan(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qtan, NULL);
}

#tanh(*args) ⇒ Calc::Q

Hyperbolic tangent

Examples:

Calc::Q(1).tanh #=> Calc::Q(0.76159415595576488812)

Parameters:

Returns:



2508
2509
2510
2511
2512
# File 'ext/calc/q.c', line 2508

static VALUE
cq_tanh(int argc, VALUE * argv, VALUE self)
{
    return trans_function(argc, argv, self, &qtanh, NULL);
}

#timesEnumerator?

Iterates the given block ‘self` times, passing in values from zero to self - 1

If no block is given, an Enumerator is returned instead.

Examples:

Calc::Q(5).times { |i| print i, " " }
#=> 0 1 2 3 4

Returns:

  • (Enumerator, nil)


580
581
582
583
584
585
586
587
# File 'lib/calc/q.rb', line 580

def times
  return to_enum(:times) unless block_given?
  i = ZERO
  while i < self
    yield i
    i += ONE
  end
end

#to_cComplex

Returns a ruby Complex number with self as the real part and zero imaginary part.

Examples:

Calc::Q(2).to_c    #=> (2+0i)
Calc::Q(2.5).to_c  #=> ((5/2)+0i)

Returns:

  • (Complex)


596
597
598
# File 'lib/calc/q.rb', line 596

def to_c
  Complex(int? ? to_i : to_r, 0)
end

#to_complexCalc::C

Returns a Calc::C complex number with self as the real part and zero imaginary part.

Examples:

Calc::Q(2).to_complex #=> Calc::C(2)

Returns:



606
607
608
# File 'lib/calc/q.rb', line 606

def to_complex
  C.new(self, 0)
end

#to_fObject

libcalc has no concept of floating point numbers. so we use ruby’s Rational#to_f



612
613
614
# File 'lib/calc/q.rb', line 612

def to_f
  to_r.to_f
end

#to_iInteger

Converts this number to a core ruby Integer.

If self is a fraction, the fractional part is truncated.

Note that the return value is a ruby Integer. If you want to convert to an integer but have the result be a ‘Calc::Q` object, use `trunc` or `round`.

Examples:

Calc::Q(42).to_i     #=> 42
Calc::Q("1e19").to_i #=> 10000000000000000000
Calc::Q(1,2).to_i    #=> 0

Returns:

  • (Integer)


2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
# File 'ext/calc/q.c', line 2528

static VALUE
cq_to_i(VALUE self)
{
    NUMBER *qself;
    ZVALUE ztmp;
    VALUE string, result;
    char *s;
    setup_math_error();

    qself = DATA_PTR(self);
    if (qisint(qself)) {
        zcopy(qself->num, &ztmp);
    }
    else {
        zquo(qself->num, qself->den, &ztmp, 0);
    }
    if (zgtmaxlong(ztmp)) {
        /* too big to fit in a long, ztoi would return MAXLONG.  use a string
         * intermediary */
        math_divertio();
        zprintval(ztmp, 0, 0);
        s = math_getdivertedio();
        string = rb_str_new2(s);
        free(s);
        result = rb_funcall(string, rb_intern("to_i"), 0);
    }
    else {
        result = LONG2NUM(ztoi(ztmp));
    }
    zfree(ztmp);
    return result;
}

#to_rObject

convert to a core ruby Rational



617
618
619
# File 'lib/calc/q.rb', line 617

def to_r
  Rational(numerator.to_i, denominator.to_i)
end

#to_s(*args) ⇒ String

Converts this number to a string.

Format depends on the configuration parameters “mode” and “display. The mode can be overridden for individual calls.

Examples:

Calc::Q(1,2).to_s        #=> "0.5"
Calc::Q(1,2).to_s(:frac) #=> "1/2"
Calc::Q(42).to_s(:hex)   #=> "0x2a"
Calc::Q(42).to_s(8)      #=> "52"

Parameters:

  • mode (String, Symbol, Integer)

    (optional) output mode, see [Calc::Config]

Returns:

  • (String)


2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
# File 'ext/calc/q.c', line 2574

static VALUE
cq_to_s(int argc, VALUE * argv, VALUE self)
{
    NUMBER *qself = DATA_PTR(self);
    char *s;
    int args;
    VALUE rs, mode;
    setup_math_error();

    args = rb_scan_args(argc, argv, "01", &mode);
    if (args == 1 && FIXNUM_P(mode)) {
        if (qisint((NUMBER *) DATA_PTR(self))) {
            rs = rb_funcall(cq_to_i(self), rb_intern("to_s"), 1, mode);
        }
        else {
            rb_raise(rb_eArgError, "can't convert non-integer to string with base");
        }
    }
    else {
        math_divertio();
        if (args == 0) {
            qprintnum(qself, MODE_DEFAULT);
        }
        else {
            qprintnum(qself, (int) value_to_mode(mode));
        }
        s = math_getdivertedio();
        rs = rb_str_new2(s);
        free(s);
    }

    return rs;
}

#trunc(*args) ⇒ Calc::Q Also known as: truncate

Truncate to a number of decimal places

Truncates to j decimal places. If j is omitted, 0 places is assumed. Truncation of a non-integer prouces values nearer to zero.

Examples:

Calc.pi.trunc    #=> Calc::Q(3)
Calc.pi.trunc(5) #=> Calc::Q(3.14159)

Parameters:

  • j (Integer)

Returns:



2619
2620
2621
2622
2623
# File 'ext/calc/q.c', line 2619

static VALUE
cq_trunc(int argc, VALUE * argv, VALUE self)
{
    return trunc_function(argc, argv, self, &qtrunc);
}

#upto(limit, &block) ⇒ Enumerator?

Iterates the given block, yielding values from ‘self` increasing by 1 up to and including `limit`

x.upto(limit) is equivalent to x.step(by: 1, to: limit)

If no block is given, an Enumerator is returned instead.

Examples:

Calc::Q(5).upto(10) { |i| print i, " " } #=> 5 6 7 8 9 10

Parameters:

  • limit (Numeric)

    highest value to return

Returns:

  • (Enumerator, nil)


634
635
636
# File 'lib/calc/q.rb', line 634

def upto(limit, &block)
  step(limit, ONE, &block)
end

#xor(*args) ⇒ Calc::Q

Bitwise exclusive or of a set of integers

xor(a, b, c, …) is equivalent to (((a ^ b) ^ c) … ) note that ^ is the ruby xor operator, not the calc power operator.

Examples:

Calc::Q(3).xor(5)           #=> Calc::Q(6)
Calc::Q(5).xor(3, -7, 2, 9) #=> Calc::Q(-12)

Returns:



647
648
649
# File 'lib/calc/q.rb', line 647

def xor(*args)
  args.inject(self, :^)
end

#zero?Calc::Q

Returns true if self is zero

Examples:

Calc::Q(0).zero? #=> true
Calc::Q(1).zero? #=> false

Parameters:

Returns:



2633
2634
2635
2636
2637
# File 'ext/calc/q.c', line 2633

static VALUE
cq_zerop(VALUE self)
{
    return qiszero((NUMBER *) DATA_PTR(self)) ? Qtrue : Qfalse;
}

#|(y) ⇒ Calc::Q

Bitwise OR

Examples:

Calc::Q(18) | 20 #=> Calc::Q(22)

Parameters:

  • y (Integer)

Returns:



499
500
501
502
503
# File 'ext/calc/q.c', line 499

static VALUE
cq_or(VALUE x, VALUE y)
{
    return numeric_op(x, y, &qor, NULL, id_or);
}

#~Object

Bitwise NOT (complement)

This is ‘-self - 1` if self is an integer, `-self` otherwise.

Examples:

~Calc::Q(7)   #=> Calc::Q(-8)
~Calc::Q(0.5) #=> Calc::Q(-0.5)


513
514
515
516
517
518
# File 'ext/calc/q.c', line 513

static VALUE
cq_comp(VALUE self)
{
    setup_math_error();
    return wrap_number(qcomp(DATA_PTR(self)));
}