我想要绘制一个图形,其值为对数刻度,这样(假设JS在这里)Math.pow(10,x)。数字范围可以是从0到n的任何正值。我发现的挑战是处理零,因为10 ^ 0是1.我尝试了以下,但我确信有更好的方法来解决这个问题:
var range = [0, 100];
exponentAdjust = 0;
if (range[0] < 1 && range[0] > 0) {
exponentAdjust = Math.log10(range[0]);
rangeExpWidth = Math.log10(range[1]) - Math.log10(range[0]);
} else if (range[0] === 0) {
exponentAdjust = -3;
rangeExpWidth = Math.log10(range[1]) - exponentAdjust;
} else {
rangeExpWidth = Math.log10(range[1]) - Math.log10(range[0]);
}
// simplified case
for (i = 0; i <= rangeExpWidth; i++) {
console.log(i + exponentAdjust, Math.pow(10, i + exponentAdjust).toFixed(2));
}
console.log('--------------');
// as used in graph, to draw the markers
width = 500;
markerXCount = 10;
markerXInterval = width / markerXCount;
console.log(markerXInterval);
for (x = 0; x <= width; x++) {
if (x % markerXInterval === 0) {
exponent = ((x / width) * rangeExpWidth) + exponentAdjust;
frequency = Math.pow(10, exponent);
console.log(x / markerXInterval, 'exp:', exponent, 'value:', Math.pow(10, exponent));
}
}
到目前为止,我看到的唯一方法是,在不增加太多复杂性的情况下,将零定义为10 ^ -1,然后根据需要进行舍入,尽管这可能会引入其他问题?