P-Adic numbers, basic: Difference between revisions
m
Improved code.
m (Improved coding.) |
m (Improved code.) |
||
Line 93:
class P_adic {
public:
// Create a
P_adic(const uint32_t& prime, int32_t numerator, int32_t denominator) : prime(prime) {
if ( denominator == 0 ) {
throw std::invalid_argument("Denominator cannot be zero");
}
Line 103:
// Process rational zero
if ( numerator == 0 ) {
digits.assign(DIGITS_SIZE, 0);▼
order = ORDER_MAX;
return;
}
// Remove multiples of 'prime' and adjust the order of the
while ( modulo_prime(numerator) == 0 ) {
numerator /= static_cast<int32_t>(prime);
Line 118 ⟶ 119:
}
// Standard calculation of
const uint64_t inverse = modulo_inverse(denominator);
while ( digits.size() < DIGITS_SIZE ) {
Line 141 ⟶ 142:
}
// Return the sum of this
P_adic add(P_adic other) {
if ( prime != other.prime ) {
throw std::invalid_argument("Cannot add p-adic's with different primes");
}
Line 151 ⟶ 152:
std::vector<uint32_t> result;
// Adjust the digits so that the
for ( int32_t i = 0; i < -order + other.order; ++i ) {
other_digits.insert(other_digits.begin(), 0);
Line 172 ⟶ 173:
}
// Return the Rational representation of this
Rational convert_to_rational() {
std::vector<uint32_t> numbers = digits;
Line 227 ⟶ 228:
}
// Return a string representation of this
std::string to_string() {
▲ digits.assign(DIGITS_SIZE, 0);
}▼
std::vector<uint32_t> numbers = digits;
pad_with_zeros(numbers);
Line 244 ⟶ 241:
for ( int32_t i = 0; i < order; ++i ) {
result += "0";
result.erase(result.begin());▼
}
Line 250 ⟶ 246:
} else {
result.insert(result.length() + order, ".");
while ( result[result.length() - 1] == '0' ) {
▲ }
}
}
private:
/**
* Create a
*
*
* 'order' > 0 shifts the vector 'order' places to the left and
* 'order' < 0 shifts the vector 'order' places to the right.
Line 269 ⟶ 267:
}
// Transform the given vector of digits representing a
// into a vector which represents the negation of the
void negate_digits(std::vector<uint32_t>& numbers) {
numbers[0] = modulo_prime(
for ( uint64_t i = 1; i < numbers.size(); ++i ) {
numbers[i] = prime - 1 - numbers[i];
Line 294 ⟶ 292:
// The given vector is padded on the right by zeros up to a maximum length of 'DIGITS_SIZE'.
void pad_with_zeros(std::vector<uint32_t>& vector) {
while ( vector.size() < DIGITS_SIZE ) {
vector.emplace_back(0);
Line 366 ⟶ 364:
{{ out }}
<pre>
-2 / 87 => ...
4 / 97 => ...
sum => ...
Rational = 154 / 8439
7-adic numbers:
5 / 8 => ...
353 / 30809 => ...
sum => ...
Rational = 156869 / 246472
</pre>
|