Compare commits

..

No commits in common. "446c8d9a6ecf81486b6f22aec13d86780a8145ee" and "311cf6ee44b55ae1b2174ee9e59d354c1da67e14" have entirely different histories.

4 changed files with 89 additions and 102 deletions

View File

@ -1,3 +1,18 @@
/*
Рассчитывает глубину провала по времени падения камня и прихода звука.
@param T измеренное полное время (с)
@param m масса камня (кг)
@param d диаметр камня (м) (предполагается сферическая форма)
@param rho плотность воздуха (кг/м³), по умолчанию 1.2
@param c скорость звука (м/с), по умолчанию 340.0
@param g ускорение свободного падения (м/с²), по умолчанию 9.81
@param Cd коэффициент лобового сопротивления, по умолчанию 0.5
@param epsilon относительная точность (м), по умолчанию 1e-3
@param maxIter максимальное число итераций, по умолчанию 20
@return глубина h (м), или null если расчёт не сошёлся
*/
fun calculateDepth(
T: Real,
m: Real,
@ -6,8 +21,8 @@ fun calculateDepth(
c: Real = 340.0,
g: Real = 9.81,
Cd: Real = 0.5,
eps: Real = 1e-3,
maxIter: Int = 100
epsilon: Real = 1e-3,
maxIter: Int = 20
): Real? {
// Площадь миделя
val r = d / 2.0
@ -21,56 +36,69 @@ fun calculateDepth(
// Функция времени падения с высоты h
fun tFall(h: Real): Real {
// Для численной стабильности при больших h используем логарифмическую форму
val arg = exp(g * h / (vTerm * vTerm))
// arcosh(x) = ln(x + sqrt(x^2 - 1))
val arcosh = ln(arg + sqrt(arg * arg - 1.0))
return vTerm / g * arcosh
}
// Полное расчётное время
// Производная времени падения по h
fun dtFall_dh(h: Real): Real {
val expArg = exp(2.0 * g * h / (vTerm * vTerm))
return 1.0 / (vTerm * sqrt(expArg - 1.0))
}
// Полное расчётное время T_calc(h) = tFall(h) + h/c
fun Tcalc(h: Real): Real = tFall(h) + h / c
// Находим интервал, содержащий корень
// Нижняя граница: глубина не может быть отрицательной
var lo = 0.0
// Верхняя граница: сначала попробуем оценку по свободному падению (без звука)
var hi = 0.5 * g * T * T // максимальная глубина, если бы не было сопротивления и звука
// Уточним hi, чтобы Tcalc(hi) было заведомо больше T
while (Tcalc(hi) < T && hi < 1e4) {
hi *= 2.0
}
// Проверка, что hi достаточно велико
if (Tcalc(hi) < T) return null // слишком большая глубина, не укладываемся в разумное
// Производная T_calc по h
fun dTcalc_dh(h: Real): Real = dtFall_dh(h) + 1.0 / c
// Бисекция
// Начальное приближение (без сопротивления)
val term = 1.0 + g * T / c
val sqrtTerm = sqrt(1.0 + 2.0 * g * T / c)
var h = (c * c / g) * (term - sqrtTerm)
// Проверка на валидность начального приближения
if (h.isNaN() || h <= 0.0) {
// Если формула дала некорректный результат, используем оценку по свободному падению
h = 0.5 * g * T * T // грубая оценка, всё равно будет уточняться
if (h.isNaN() || h <= 0.0) return null
}
// Итерации Ньютона
var iter = 0
var h = (lo + hi) / 2.0
while (iter < maxIter && (hi - lo) > eps) {
while (iter < maxIter) {
val f = Tcalc(h) - T
if (abs(f) < eps) break
if (f > 0) {
hi = h
} else {
lo = h
val df = dTcalc_dh(h)
// Если производная близка к нулю, выходим
if (abs(df) < 1e-12) return null
val hNew = h - f / df
// Проверка сходимости
if (abs(hNew - h) < epsilon) {
return hNew
}
h = (lo + hi) / 2.0
h = hNew
iter++
println("iter: $iter: $h")
}
return h
// Не сошлось за maxIter
return null
}
// Пример: T=12 секунд
val T = 26.0
// Пример использования
val T = 6.0 // секунды
val m = 1.0 // кг
val d = 0.1 // м
val d = 0.1 // м (10 см)
val depth = calculateDepth(T, m, d)
if (depth != null) {
println("Глубина: %.2f м"(depth))
// Для проверки выведем теоретическое время при найденной глубине
// (можно добавить функцию для самопроверки)
} else {
println("Расчёт не сошёлся")
}

View File

@ -436,12 +436,6 @@ class Compiler(
}
}
private fun rememberModuleReferencePos(name: String, pos: Pos) {
if (!moduleReferencePosByName.containsKey(name)) {
moduleReferencePosByName[name] = pos
}
}
private fun predeclareClassMembers(target: MutableSet<String>, overrides: MutableMap<String, Boolean>) {
val saved = cc.savePos()
var depth = 0
@ -954,7 +948,7 @@ class Compiler(
}
}
captureLocalRef(name, slotLoc, pos)?.let { ref ->
rememberModuleReferencePos(name, pos)
moduleReferencePosByName.putIfAbsent(name, pos)
resolutionSink?.reference(name, pos)
return ref
}
@ -1048,7 +1042,7 @@ class Compiler(
moduleEntry.isDelegated
)
captureLocalRef(name, moduleLoc, pos)?.let { ref ->
rememberModuleReferencePos(name, pos)
moduleReferencePosByName.putIfAbsent(name, pos)
resolutionSink?.reference(name, pos)
return ref
}
@ -1075,7 +1069,7 @@ class Compiler(
strictSlotRefs
)
}
rememberModuleReferencePos(name, pos)
moduleReferencePosByName.putIfAbsent(name, pos)
resolutionSink?.reference(name, pos)
return ref
}
@ -1110,7 +1104,7 @@ class Compiler(
val slot = lookupSlotLocation(name)
if (slot != null) {
captureLocalRef(name, slot, pos)?.let { ref ->
rememberModuleReferencePos(name, pos)
moduleReferencePosByName.putIfAbsent(name, pos)
resolutionSink?.reference(name, pos)
return ref
}
@ -1137,7 +1131,7 @@ class Compiler(
strictSlotRefs
)
}
rememberModuleReferencePos(name, pos)
moduleReferencePosByName.putIfAbsent(name, pos)
resolutionSink?.reference(name, pos)
return ref
}

View File

@ -7664,9 +7664,7 @@ class BytecodeCompiler(
private fun noteScopeSlotRef(slot: Int, pos: Pos) {
if (slot >= scopeSlotCount) return
val key = scopeKeyByIndex.getOrNull(slot) ?: return
if (!scopeSlotRefPosByKey.containsKey(key)) {
scopeSlotRefPosByKey[key] = pos
}
scopeSlotRefPosByKey.putIfAbsent(key, pos)
}
private fun resolveSlot(ref: LocalSlotRef): Int? {
@ -7677,15 +7675,11 @@ class BytecodeCompiler(
val localIndex = localSlotIndexByKey[key]
if (localIndex != null) return scopeSlotCount + localIndex
scopeSlotMap[key]?.let {
if (!scopeSlotRefPosByKey.containsKey(key)) {
scopeSlotRefPosByKey[key] = ref.pos()
}
scopeSlotRefPosByKey.putIfAbsent(key, ref.pos())
return it
}
scopeSlotIndexByName[ref.name]?.let {
if (!scopeSlotRefPosByKey.containsKey(key)) {
scopeSlotRefPosByKey[key] = ref.pos()
}
scopeSlotRefPosByKey.putIfAbsent(key, ref.pos())
return it
}
}
@ -7699,9 +7693,7 @@ class BytecodeCompiler(
}
val resolved = scopeSlotMap[scopeKey]
if (resolved != null) {
if (!scopeSlotRefPosByKey.containsKey(scopeKey)) {
scopeSlotRefPosByKey[scopeKey] = ref.pos()
}
scopeSlotRefPosByKey.putIfAbsent(scopeKey, ref.pos())
}
return resolved
}
@ -7716,9 +7708,7 @@ class BytecodeCompiler(
val scopeKey = ScopeSlotKey(refScopeId(ref), refSlot(ref))
val resolved = scopeSlotMap[scopeKey]
if (resolved != null) {
if (!scopeSlotRefPosByKey.containsKey(scopeKey)) {
scopeSlotRefPosByKey[scopeKey] = ref.pos()
}
scopeSlotRefPosByKey.putIfAbsent(scopeKey, ref.pos())
}
return resolved
}

View File

@ -284,31 +284,6 @@ class DecimalModuleTest {
)
}
@Test
fun testDecimalTruncateToTwoFractionDigitsViaGlobalRound() = runTest {
val scope = Script.newScope()
scope.eval(
"""
import lyng.decimal
fun trunc2(x: Decimal): Decimal {
val scaled = x * 100.d
val whole = if (scaled >= 0.d) {
floor(scaled) as Decimal
} else {
ceil(scaled) as Decimal
}
whole / 100.d
}
assertEquals("12.34", trunc2("12.349".d).toStringExpanded())
assertEquals("12.34", trunc2("12.340".d).toStringExpanded())
assertEquals("-12.34", trunc2("-12.349".d).toStringExpanded())
assertEquals("-12.34", trunc2("-12.340".d).toStringExpanded())
""".trimIndent()
)
}
@Test
fun testDecimalMathHelpersFallbackThroughRealTemporarily() = runTest {
val scope = Script.newScope()