gpt4 book ai didi

javascript - 如何在 Javascript 中将小数(基数 10)转换为小数基数(即基数 3/2)

转载 作者:行者123 更新时间:2023-12-05 02:49:56 24 4
gpt4 key购买 nike

我发现很多资源都在讨论基数转换算法和使用内置 Javascript 函数将十进制转换为二进制或十六进制,但是我找不到任何关于如何转换为任何小数基数(例如基数 3/2)的资源. sesquinary 数字系统非常有趣,我希望能够使用它,但我找不到任何方法将其从 Decimal 转换为它。

半数系统如下:1、2、20、21、22、210、211、212、2100、2101等

我找不到任何可靠的方法来转换它。这是我到目前为止的代码:

function decimalToBase(number, base) {
let digitArray = [];
let quotient;
let remainder;

for (let i = 0; i < 16; i++) {
quotient = Math.floor(number / base);
remainder = number % base;
digitArray.unshift(remainder);
number = quotient;

if (quotient == 0){
break;
}
}
console.log(digitArray)
}

它适用于 10 以下的整数基数,但如果我输入像 3/2 这样的小数基数,那么我会得到带小数的结果:

[1, 0.5, 1, 0] // When It should be: [2, 1, 0]

如有任何帮助,我们将不胜感激。

最佳答案

对于 3/2 特定情况,this article詹姆斯·普罗普 (James Propp) 公开了几种方法,其中一种是西蒙·诺顿 (Simon Norton) 在尾注中描述的:

It’s based on the fact that when n is written as 3k + r, where the remainder r is 0, 1, or 2, the sesquinary representation of n is equal to the sesquinary representation of 2k, with the digit r tacked on at the end. This gives us a quick way to write the sesquinary representation of n from right to left via a process of repeatedly dividing by three, rounding down, and doubling.

go read the full article

他们还提供了一些 Mathematica 代码来运行它。

S[n_] := If[n < 3, {n}, Append[S[2 Floor[n/3]], Mod[n, 3]]]

我真的不懂Mathematica,所以我不能真正用js一对一重写它,但如果我正确理解算法,那将是这样的:

const decimalToSesquinary = (n) => {
const res = [];
while (n) {
const k = Math.floor(n / 3);
res.push(n % 3);
n = k * 2;
}
return res.reverse().join("");
};

console.log(decimalToSesquinary(6)) // expected "210"
console.log(decimalToSesquinary(7)) // expected "211"
console.log(decimalToSesquinary(8)) // expected "212"
console.log(decimalToSesquinary(100)) // expected "212001201"

关于javascript - 如何在 Javascript 中将小数(基数 10)转换为小数基数(即基数 3/2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63838420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com