List Manipulation

List Manipulation

avinash00002002
Collaborator Collaborator
320 Views
23 Replies
Message 1 of 24

List Manipulation

avinash00002002
Collaborator
Collaborator

Hi!

 

I have some lists one of them I am putting here for help.

 

original

(25 299.4 100.3 100.8 399.3 118.9 25)

 

convert to 0.5  precision

(25.0 299.5 100.5 101.0 399.5 119.0 25.0)

 

I want to convert to 0.5 but the total of all members in a list is 1069.5 but I need to convert in 1070.

final summation of list members shall be 0.0 not .5 

 

Thanks,

avinash

0 Likes
321 Views
23 Replies
Replies (23)
Message 21 of 24

Kent1Cooper
Consultant
Consultant

@avinash00002002 wrote:

... summation of list of members are 0.0 it will also adjust members value.


If the members of the list are all rounded to the nearest 0.5, and if the summation of those members comes to a xx.5 value, by what standard should it decide which of the members to adjust to make the summation to the nearest 0.0 [whole number]?  Presumably it would adjust only one, whether up or down, but there must be a determination of which one.

Kent Cooper, AIA
0 Likes
Message 22 of 24

calderg1000
Mentor
Mentor

Regards @avinash00002002 

Try this code.

;;;___
(defun ssum (lst / j n dj nlst st)
  (foreach j lst
    (setq dj (- j (fix j)))
    (cond ((= dj 0.) (setq n j))
          ((< dj 0.5) (setq n (+ (fix j) 0.5)))
          ((> dj 0.5) (setq n (+ (fix j) 1.0)))
          (t nil)
    )
    (setq nlst (cons n nlst))
  )
  (setq st  (apply '+ nlst)
        ndj (- st (fix st))
  )
  (if (= ndj 0.5)
    (setq st (+ st 0.5))
  )
  (print st)
  (print (reverse nlst))
)
;;;___
(setq lst '(25 299.4 100.3 100.8 399.3 118.9 25))
(ssum lst)
;1070.0 
;(25 299.5 100.5 101.0 399.5 119.0 25)

 


Carlos Calderon G
EESignature
>Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

0 Likes
Message 23 of 24

kerry_w_brown
Advisor
Advisor

For the original Poster @avinash00002002 

Was passing and marvelled that this thread has reached 22 posts.
For giggles I added this to VSCode and added 3 prompts to GPT-5.
Note that the 3 prompts could have been combined but I chose 3 as an example of building a solution.

Original Code.

;| Using AutoLisp for AutoCAD 2025
Change all items to the nearest 0.5 precision.
|;

;; Original sample list:
(setq original_list '(25 299.4 100.3 100.8 399.3 118.9 25))

 

Prompt 01:

Please solve as documented.


Prompt 02

Excellent, now we want to sum the `rounded_list` values please

Prompt 03

That result is satisfactory. Now, please round the returned value from `sumList` (if it is fractional), save the value and display the summed value.

 

These prompts were based on the information in the initial post.

It seems to me that you could have had the following unedited solution in 10 minutes instead of waiting 3 days.

;| Using AutoLisp for AutoCAD 2025
Change all items to the nearest 0.5 precision.
This sample defines:
	- original_list : the source numeric list
	- round-to-0.5  : helper function (value -> nearest 0.5)
	- roundListToHalf : maps a list to nearest 0.5 values
	- FIRSTTEST command: prints both lists to command line
 |;

;; Original sample list (fixed syntax: remove extraneous paren before first 25)
(setq original_list '(25 299.4 100.3 100.8 399.3 118.9 25))

;; Rounds a real number to the nearest 0.5 increment
;; v : real number
;; return: real rounded to nearest multiple of 0.5
;; NOTE: Using (fix (+ 0.5 x)) only works for positive numbers. For negatives
;; we mirror to positive, round, then restore the sign so that -0.3 -> -0.5 (nearest)

 (defun round-to-0.5 (v / a)
	(setq a (abs v))
	(/ (* (if (minusp v) -1.0 1.0) (float (fix (+ 0.5 (* a 2.0))))) 2.0)
) 

;; Alternate (more explicit) method using rounding of scaled value:
;;(defun round-to-0.5 (v) (/ (float (fix (+ 0.5 (* v 2.0)))) 2.0))

;; Map list values to nearest 0.5
(defun roundListToHalf (lst /)
	(if lst
		(cons (round-to-0.5 (car lst)) (roundListToHalf (cdr lst)))
		nil
	)
)

;; Sum a list of numbers (tail-recursive style helper)
(defun sumList (lst / acc)
	(setq acc 0.0)
	(while lst
		(setq acc (+ acc (car lst))
					lst (cdr lst))
	)
	acc
)

;; Precompute (optional) or could compute inside command each time.
(setq rounded_list (roundListToHalf original_list))

;; Store the floating sum and an integer-rounded version (nearest integer)
;; If you prefer always recomputing, move these inside the command.
(setq rounded_sum        (sumList rounded_list))
(setq rounded_sum_int    (fix (+ 0.5 rounded_sum))) ; nearest whole number

;; Command to test:  (type FIRSTTEST at command line after loading)
(defun c:FIRSTTEST (/)
	;; Recompute in case user altered original_list after load
	(setq rounded_list     (roundListToHalf original_list)
				rounded_sum      (sumList rounded_list)
				rounded_sum_int  (fix (+ 0.5 rounded_sum)))
	(princ "\nOriginal List: ") (princ original_list)
	(princ "\nRounded  List: ") (princ rounded_list)
	(princ "\nSum (float):   ") (princ rounded_sum)
	(princ "\nSum (integer): ") (princ rounded_sum_int)
	(princ "\nDone. ")
	(princ)
)

;; Silent load
(princ "\nTest_List_Manipulation.lsp loaded. Use FIRSTTEST.")
(princ)

 

All comments are added by the CHAT bot. 

I haven't tried to refactor it to be more streamlined . . . but the chat bot could do that for you if needed.
The actual CHAT responses are several pages long and contain a complete explaination of all the code and the thinking behind it,

which would be ideal to learn from.

To me this is a reasonable sample of modular programming which improves the learning process as well as allows for progressive testing to proove the concepts and the code functionallity.

 

Live long and prosper,

Regards, 


// Called Kerry or kdub in my other life.

Everything will work just as you expect it to, unless your expectations are incorrect. ~ kdub
Sometimes the question is more important than the answer. ~ kdub

NZST UTC+12 : class keyThumper<T> : Lazy<T>;      another  Swamper
0 Likes
Message 24 of 24

kerry_w_brown
Advisor
Advisor

For completeness, this is the full CHAT response file:

 

kdub-nz: Please solve as documented.

GitHub Copilot: Reading the full file to ensure correct and safe update with rounding logic. 

Read [](file:///d%3A/SteelToolsSource_241/__OddBits/Test_List_Manipulation.lsp)

Created 2 todos

Applying patch to implement rounding functionality and command. 

Using "Apply Patch"
Starting (2/2) *Explain usage to user*

Updating rounding function to correctly handle negative numbers and adding note. 

Using "Apply Patch"
Completed (2/2) *Explain usage to user*

Implemented the rounding logic and test command.

## What’s in Test_List_Manipulation.lsp
- Fixed the original list syntax (removed stray parenthesis).
- Added `round-to-0.5` that correctly handles positive and negative numbers.
- Added `roundListToHalf` to map any list.
- Created `rounded_list` as the processed version of `original_list`.
- Added command `TLMTST` to print both lists.
- Silent load message hints usage.

## How to Use in AutoCAD
1. Load the file:
   Command: APPLOAD
   Browse to Test_List_Manipulation.lsp and load it.
   (You’ll see: “Test_List_Manipulation.lsp loaded. Use TLMTST.”)
2. Run the test:
   Type: TLMTST
3. Expected output (rounded to nearest 0.5):
   Original List: (25 299.4 100.3 100.8 399.3 118.9 25)
   Rounded  List: (25.0 299.5 100.5 101.0 399.5 119.0 25.0)

## Re-using the Functions
To round any list of reals:
  (roundListToHalf '(1.12 2.74 -0.31 -0.76))
Returns:
  (1.0 2.5 -0.5 -1.0)

## Notes / Tweaks
- If you prefer recomputing `rounded_list` each run (in case you later change `original_list`), move `(setq rounded_list ...)` inside the command definition.
- For performance on very large lists, a tail‑recursive or iterative version could be added, but this is fine for typical CAD data sizes.

Let me know if you’d like a version that rounds to an arbitrary increment (e.g., 0.25, 5, etc.).

Made changes.

kdub-nz: Excellent, now we want to sum the rounded_list values please

GitHub Copilot: Reading current file to append sum functionality without overwriting user edits. 

Read [](file:///d%3A/SteelToolsSource_241/__OddBits/Test_List_Manipulation.lsp)

Starting (1/1) *Add sum functionality*

Applying patch to add sum function and enhance command output with total. 

Using "Apply Patch"

Using "Apply Patch"

Completed (1/1) *Add sum functionality*

Added a `sumList` function and updated the `FIRSTTEST` command to display the sum of `rounded_list`.

Now when you run FIRSTTEST you’ll see:
Original List: (...)
Rounded  List: (...)
Sum (rounded): <value>

Because the rounding yields:
(25.0 299.5 100.5 101.0 399.5 119.0 25.0)
The sum should report: 1069.5

If you later change `original_list`, just re-run:
  (setq rounded_list (roundListToHalf original_list))
then run FIRSTTEST again to get an updated sum.

Want an optional second command that recomputes everything each time (no reliance on stored `rounded_list`)? Just say the word and I can add it.

Made changes.

kdub-nz: That result is satisfactory. Now, please round the returned value from `sumList`  (if it is fractional), save the value and display the summed value.

GitHub Copilot: Adding integer rounding of the summed list value, storing it, and displaying both raw and integer-rounded totals. 

Starting (1/1) *Add integer rounding of sum*

Reading current file to determine insertion point for new code storing rounded sum. 

Read [](file:///d%3A/SteelToolsSource_241/__OddBits/Test_List_Manipulation.lsp)

Applying patch to store raw sum and integer-rounded sum, showing both. 

Using "Apply Patch"

Completed (1/1) *Add integer rounding of sum*

Added persistent variables `rounded_sum` (float) and `rounded_sum_int` (nearest integer) and updated `FIRSTTEST` to recompute and display:

- Sum (float): exact summed value of the half-rounded list
- Sum (integer): nearest whole number using standard rounding

How it works:
1. When you run FIRSTTEST it recalculates `rounded_list`, `rounded_sum`, and `rounded_sum_int` so any edits to `original_list` are reflected.
2. Integer rounding uses (fix (+ 0.5 value)) which is fine for non-negative totals; if you anticipate negative totals, we can switch to a sign‑aware helper.

If you’d like:
- Rounding to the nearest N (e.g., 5, 10) for the total
- Formatting with fixed decimals
- Returning these values in a list or writing them to a file

Just let me know and I can extend it. Want any of those extras?

Made changes.

 


// Called Kerry or kdub in my other life.

Everything will work just as you expect it to, unless your expectations are incorrect. ~ kdub
Sometimes the question is more important than the answer. ~ kdub

NZST UTC+12 : class keyThumper<T> : Lazy<T>;      another  Swamper
0 Likes